I tried developing browser geolocation, but it seems geolocation quickly return a value when it is still searching for my location.
Example of my script:
function updateCoordinate() {
navigator.geolocation.getCurrentPosition(
function (position) {
setTimeout(function() {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
var serializeCookie = serialize(returnValue);
$.cookie('geolocation', serializeCookie);
return serializeCookie;
}, 5000);
},
function () {
alert('Sorry, we are failed to get your location')
}, {timeout: 5000}
)
}
If we execute this script updateCoordinate
, the function will return undefined
. But after a moment if we check the cookie it set right the coordinate.
How to make getCurrentPosition waiting until get exact coordinate before returning the value?
Geolocation getCurrentPosition() API The getCurrentPosition method retrieves the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. The location information is returned in a Position object.
What does showPosition() returns? Explanation: showPosition() method returns both latitude and longitude of user.
The getCurrentPosition() method returns the current position of the device.
The Geolocation method watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function.
Use a callback, not a timeout which will end you up in all sorts of problems. Something along the lines of:
// Here you pass a callback function as a parameter to `updateCoordinate`.
updateCoordinate(function (cookie) {
console.log(cookie);
});
function updateCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
var serializeCookie = serialize(returnValue);
$.cookie('geolocation', serializeCookie);
// and here you call the callback with whatever
// data you need to return as a parameter.
callback(serializeCookie);
}
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With