Openlayers 3 vector source issue - openlayers-3

Inside the ajax callback I have all the features as expected, but I don't have them outside.
What am I missing ?
var geojsonSource = new ol.source.Vector();
$.ajax('assets/data/data.geojson').then(function(response) {
var geojsonFormat = new ol.format.GeoJSON();
var features = geojsonFormat.readFeatures(response, {featureProjection: 'EPSG:4326'});
geojsonSource.addFeatures(features);
console.log(geojsonSource.getFeatures()); // this work
});
console.log(geojsonSource.getFeatures()); // this doesn't work

Everything's fine with your snippet. As #kryger said, AJAX is Asynchronous Javascript and XML. So, register a listener to know when your features are added to the source, like:
geojsonSource.on('addfeature', function(event){
console.log(geojsonSource.getFeatures());
});

Related

OpenLayers 3 - How can I abort pending ajax requests - ol.source.GeoJSON

I'm adding a layer with a source requested by ol.source.GeoJSON on moveend. How can I abort pending ajax requests if the map is panned again before the request finishes?
map.on('moveend', function(){
map.removeLayer(highlightedLayer);
var theSource = new ol.source.GeoJSON({
url: 'wfs.php?bbox='+bbox
});
var highlightedSource = new ol.source.GeoJSON({});
theSource.on('change', function(e){
if(theSource.getState() == 'ready'){
var features = theSource.getFeatures();
$.each(features, function(k,v){
if(v.n.filter == 'include'){
highlightedSource.addFeature(features[k]);
}
});
highlightedLayer.setSource(highlightedSource);
map.addLayer(highlightedLayer);
}
});
});
Instead of adding the layer directly at the moveend you could fetch the GeoJson with ajax (which can be cancelled) and when complated add geojson data using the object paramter instead of the url.
Heres the docs for GeoJSON source:
http://openlayers.org/en/v3.4.0/apidoc/ol.source.GeoJSON.html?unstable=true
Heres how you cancel a ajax request:
Abort Ajax requests using jQuery
Hope this helps you.

Ionic Prepopulated Database with Antair Cordova SQLitePlugin [help request]

____ INTRO
Hello everyone, first of all, three clarifications:
My english is not good, so I beg your pardon in advance for my mistakes,
I'm a newbie so forgive me for inaccuracies,
I have previously searched and tried the solutions I found on the internet but still I can not solve the problem of embedding a prepopulated database.
____ THE GOAL
I want to develop an app for iOS and Android with a prepopulated database.
Just for example, the database consists of 15.000 records each one made of three key-value pair (id, firstname and lastname).
___ WHAT I DID
Steps:
ionic start myapp blank
cd myapp
ionic platform add ios
ionic platform add android
Then I created an sqlite database for testing purpose, named mydb.sqlite, made of one table people containing two id, firstname, lastname records.
I decided to use the following plugin: https://github.com/Antair/Cordova-SQLitePlugin
That's because it can be installed with cordova tool.
ionic plugin add https://github.com/Antair/Cordova-SQLitePlugin
(Alert: I think that the instructions on the website show an incorrect reference - "cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin" - which refers to another plugin).
Then, following the instructions on the plugin website, I copied the database to myapp/www/db/ so that it can now be found at myapp/www/db/mydb.sqlite
I modified the index.html including the SQLite plugin just after the default app.js script:
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="SQLitePlugin.js"></script>
I also write some lines of code in index.html file to show a button:
<ion-content ng-controller="MyCtrl">
<button class="button" ng-click="all()">All</button>
</ion-content>
Finally I had modified ./js/app.js:
// Ionic Starter App
var db = null;
angular.module('starter', ['ionic' /* What goes here? */ ])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// some predefined code has been omitted
window.sqlitePlugin.importPrepopulatedDatabase({file: "mydb.sqlite", "importIfExists": true});
db = window.sqlitePlugin.openDatabase({name: "mydb.sqlite"});
}); // $ionicPlatform.ready
}) // .run
.controller('MyCtrl', function($scope){
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
}); // .controller
___ THE PROBLEM
I don't know how to proceed in the controller section to query all the records (just an example of query) and show the results in the console.log.
I think that the following code must be completed in some way:
angular.module('starter', ['ionic' /* What goes here? */ ])
And also the code inside controller section must be completed:
$scope.all = function(){
var query = "SELECT * FROM people";
// I don't know how to proceed
}; // $scope.all
___ FINAL THANKS
Thank you in advance for the help you will give to me.
So this guy's code has helped a lot to encapsulate my DAL. I highly recommend that you use he's code pretty much verbatim.
https://gist.github.com/jgoux/10738978
You'll see he has the following method:
self.query = function(query, bindings) {
bindings = typeof bindings !== 'undefined' ? bindings : [];
var deferred = $q.defer();
self.db.transaction(function(transaction) {
transaction.executeSql(query, bindings, function(transaction, result) {
deferred.resolve(result);
}, function(transaction, error) {
deferred.reject(error);
});
});
return deferred.promise;
};
Let's break this down a bit. The query function takes a query string (the query param) and a list of possible bindings for ? in a query like "SELECT * FROM A_TABLE WHERE ID = ?". Because he's code is a service, the self value points to the service itself for all future invocations. The function will execute a transaction against the db, but it returns a promise that is only fulfilled once the db comes back.
His service provides a second helper function: fetchAll.
self.fetchAll = function(result) {
var output = [];
for (var i = 0; i < result.rows.length; i++) {
output.push(result.rows.item(i));
}
return output;
};
fetchAll will read the rows in their entirety into an array. The result param for fetchAll is the result variable passed in the query function's promise fulfillment.
If you copy and paste his code into your service file, you now have a bonafide DB service. You can wrap that service up in a DAL. Here's an example from my project.
.service('LocationService', function ($q, DB, Util) {
'use strict';
var self = this;
self.locations = [];
self.loadLocked = false;
self.pending = [];
self.findLocations = function () {
var d = $q.defer();
if (self.locations.length > 0) {
d.resolve(self.locations);
}
else if (self.locations.length === 0 && !self.loadLocked) {
self.loadLocked = true;
DB.query("SELECT * FROM locations WHERE kind = 'active'")
.then(function (resultSet) {
var locations = DB.fetchAll(resultSet);
self.locations.
push.apply(self.locations, locations);
self.loadLocked = false;
d.resolve(self.locations);
self.pending.forEach(function (d) {
d.resolve(self.locations);
});
}, Util.handleError);
} else {
self.pending.push(d);
}
return d.promise;
};
})
This example is a bit noisy since it has some "threading" code to make sure if the same promise is fired twice it only runs against the DB once. The general poin is to show that the DB.query returns a promise. The "then" following the query method uses the DB service to fetchAll the data and add it into my local memory space. All of this is coordinated by the self.findLocations returning the variable d.promise.
Yours would behalf similarly. The controller could have your DAL service, like my LocationService, injected into it by AngularJS. If you're using the AngularJS UI, you can have it resolve the data and pass it into the list.
Finally, the only issue I have with the guy's code is that the db should come from this code.
var dbMaker = ($window.sqlitePlugin || $window);
The reason for this is that the plugin does not work within Apache Ripple. Since the plugin does a fine job mirroring the Web SQL interface of the browser, this simple little change will enable Ripple to run your Ionic Apps while still allowing you to work your SQLite in a real device.
I hope this helps.

Titanium isn't posting values to ColdFusion

This is my Titanium code:
var loginReq = Titanium.Network.createHTTPClient({
onload: function(e){
// just displays the response
var webview = Titanium.UI.createWebView({html:this.responseText});
win.add(webview);
}
});
loginReq.open("POST",url);
var params = {
email: email.value,
passowrd: password.value
};
loginReq.send(params); // this is sending nothing according to a CF variable dump
The ColdFusion page just dumps all the variables, and it shows up on the iPhone emulator. But it's giving me an empty struct for the variables, which means no variables are actually getting sent in.
How do I fix my Titanium code to actually post data?
If you want to send post data to a script you will have to to set the header accordingly:
loginReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
If you are sending JSON data to an API, you might need to stringify your parameters to send them:
loginReq.send(JSON.stringify(params));
Edit:
According to the docs this is done automatically (see comments). In some of my network clients I had to do that explicitly, though...
Moreover, you might also want to implement the onerror callback, so in case your call fails for any reason you will know why:
var loginReq = Titanium.Network.createHTTPClient({
onload: function(e){
// just displays the response
var webview = Titanium.UI.createWebView({html:this.responseText});
win.add(webview);
},
onerror: function(e) {
Ti.API.debug('Status: ' + this.status);
Ti.API.debug('Response: ' + this.responseText);
}
});

Attaching event handlers for dynamically created jQuery Mobile pages

In my jQuery Mobile application, I am creating some dynamic pages.Here is the code
function createPages()
{
$header = "<header data-role='header'><h1>Dynamically created pages</h1></header>";
$content = "<div data-role='content' class='content'><p>This is a dynamically generated page</p></div>";
$footer = "<div data-role='footer'><h1>Audimax</h1></footer>";
for($i=1;$i<=5;$i++)
{
$section= "<section id='"+"#fav"+$i+"' data-role='page' data-url='"+"fav"+$i+"' class='dynamic'>";
$new_page = $($section+$header+$content+$footer+"</section>");
$new_page.appendTo($.mobile.pageContainer);
}
}
The pages are being created properly and being added to the DOM and I can navigate to them. The problem is that I simply can,t attach any event handlers to the dynamic pages.I am using ids of the dynamic pages with jquery "live" but to no avail.Any help is greatly appreciated.
Why not bind the event handlers when you add the new pseudo-page to the DOM?
function pageShowFunction () {
console.log(this.id + ' has triggered the `pageShow` event!');
}
function createPages()
{
$header = "...";
$content = "...";
$footer = "...";
for($i=1;$i<=5;$i++)
{
$section= "<section id='"+"#fav"+$i+"' data-role='page' data-url='"+"fav"+$i+"' class='dynamic'>";
$new_page = $($section+$header+$content+$footer+"</section>").bind('pageshow', pageShowFunction);
$new_page.appendTo($.mobile.pageContainer);
}
}
It's normally better to bind directly to elements rather than delegating the event handling.
P.S. You didn't post your event binding code so I can't give any specific comments on that code, perhaps you can update your question with that code if this doesn't fix your issue.
Upgrade the jquery core to 1.7.1 from
http://jquery.com/download/
and then
$(selector).live( eventName, function(){} );
Can be replaced with the following on signature
$(document).on( eventName, selector, function(){} );
It then works for dynamic elements.

jquerymobile and AJAX

seems to me that I didn't fully understand the concept behind jquerymobile, because I have no idea how to solve this issue.
What I want to do is load some HTML Content via AJAX, according to location.hash, put it into a new page and load this page.
But if I create a page myself by using the pagebeforechange event, jquerymobile just ignores it, creates its own div and my content won't be displayed.
How do I have to do it?
Edit:
This is how I am currently doing it, but it wont't work.
$(function() {
getPageContent(top.location.href, false);
$(document).bind( "pagebeforechange", function( e, data ) {
getPageContent(data.toPage, true);
});
});
function getPageContent(pageUrl, changedPage) {
var re = /.*\/#(.*)/;
var result;
result = re.exec(pageUrl);
window.page = result[1].substr(0,3);
window.id = result[1].substr(3);
window.ajaxUrl = "request.php?page="+window.page+"&id="+window.id;
$.ajax({
url: window.ajaxUrl,
success: function(data) {
if(data.error) {
alert(data.error);
}
else if(data.data) {
if(changedPage) {
changePage(data.data));
}
else {
$('#content[role="main"]').html(atob(data.data));
setupPage();
}
}
else {
alert("UNKNOWN ERROR: "+data);
}
}
});
}
function changePage(html) {
var div = "<div></div>";
var newPage = $(div).attr("data-role", "page").attr("data-url", window.page+window.id);
var header = $(div).attr("data-role", "header");
var content = $(div).attr("data-role", "content");
var footer = $(div).attr("data-role", "footer");
$("body").append(newPage);
newPage.append(header, content, footer);
content.html(html);
newPage.page();
}
Complete edit of the whole answer:
First. Set your body id to id=body. Then when you want to load the new page and change to it, use an ajax call like this:
$.get(window.ajaxUrl, function(data){
$('#body').append("<div id='newPage' data-role='page'></div>"); //Creates a new page.
$('#newPage').html(data); //Loads the html content into the new page.
$.mobile.changePage('#newPage'); //Navigates to the new page.
}
This sends an ajax call with the method GET to the url found in your window.ajaxUrl. If the call is successful, it creates a new page named "newPage", and fills it with the data received from the ajax call. Then redirects to the newly created page.
This jsFiddle shows the basics of how it works. However, it doesn't use any ajax call.
You have to refresh the page with jQueryMobile :
$("#your-page").trigger("create");
--Edit
<script>
$("#thepage").live("pageshow", function(){
$("#thepage).trigger("create");
});
</script>
Change the content of #thepage before 'pageshow' event
It does this for you automatically - just make a regular link to the page and jquery mobile will shwo the loading spinner, load it in the background via ajax, then transition to the new page.
Make sure all your pages are decide with unique IDs and data-role='page'. Check out the start guide here:
http://jquerymobile.com/demos/1.1.0/docs/about/getting-started.html

Resources