Reputation: 322
I'm trying to use geolocation to add current latitude and longitude to an object I can use later in an application, like so:
var loc = {
get_latlong: function() {
var self = this,
update_loc = function(position) {
self.latitude = position.coords.latitude;
self.longitude = position.coords.longitude;
};
win.navigator.geolocation.getCurrentPosition(update_loc);
}
}
When I run loc.get_latlong()
then console.log(loc)
I can see the object, the method and the two properties in the console.
However when I try console.log(loc.latitude)
or console.log(loc.longitude)
it's undefined.
What is that all about?
Upvotes: 1
Views: 182
Reputation: 17444
As others mentioned you can't expect result of an async call to come instantly, you need to use a callback. Something like this:
var loc = {
get_latlong: function (callback) {
var self = this,
update_loc = function (position) {
self.latitude = position.coords.latitude;
self.longitude = position.coords.longitude;
callback(self);
}
win.navigator.geolocation.getCurrentPosition(update_loc);
}
}
then you call it using:
loc.get_latlong(function(loc) {
console.log(loc.latitude);
console.log(loc.longitude);
});
Upvotes: 2