I’m trying to create a function that returns a object with information of a callback:
var geoloc;
var successful = function (position) {
geoloc = {
longitude: position.coords.longitude,
latitude: position.coords.latitude
};
};
var getLocation = function () {
navigator.geolocation.getCurrentPosition(successful, function () {
alert("fail");
});
return geoloc;
};
How can I do this? The function getLocation return null value before successful is executed.
Thanks!
Callbacks are used because the function is asynchronous. The callback runs at some point in the future.
So, yes
getLocationreturns before the callback is triggered. That’s how asynchronous methods work.You cannot wait for the callback, that’s not how it works. You can add a callback to
getLocation, that runs once it’s done.Now instead of doing
var x = getLocation()and expecting a return value, you call it like this: