Skip to content Skip to sidebar Skip to footer

Js Geolocation Wait Until Success Before Return Value

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(

Solution 1:

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);
      }
    )
}

Post a Comment for "Js Geolocation Wait Until Success Before Return Value"