Reputation: 1124
I am using phonegap in android development. I wrote that PoC, however I can not figure out why it does not change the latitude of profile variable. Actually
alert(profile.latitude);
runs before the
geoCode.setLocation();
here is my code;
document.addEventListener("deviceready", onDeviceReady, false);
var profile = {
name: "",
id: "red",
latitude: "xx",
longtitude: "",
setCoordinates: function (latit, longt) {
this.latitude = latit;
this.longtitude = longt;
}
};
var geoCode = {
onSuccess: function (position) {
profile.latitude = position.coords.latitude;
},
onError: function (error) {
},
setLocation : function () {
navigator.geolocation.getCurrentPosition(this.onSuccess, this.onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation();
//alert("2");
alert(profile.latitude);
};
thanks in advance
Upvotes: 1
Views: 959
Reputation: 29547
navigator.geolocation.getCurrentPosition is an asynchronous function. You need to do something like :
var geoCode = {
setLocation : function (callback) {
onSuccess: function (position) {
callback(position.coords.latitude);
},
onError: function (error) {
},
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
};
// Wait for PhoneGap to load
//
function onDeviceReady() {
geoCode.setLocation(function(latitude) {
alert(latitude);
});
};
Upvotes: 1
Reputation: 23273
Quite simply it is because the call to navigator.geolocation.getCurrentPosition() is an asynchronous call. Thereby the execution of the program continues and you see the alert. Sometime after the alert is show the onSuccess call of your geoCode class is called updating the profile.latitude value.
Upvotes: 0