JS Geolocation wait until success before return value

后端 未结 1 1707
小蘑菇
小蘑菇 2020-12-18 07:29

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:

<         


        
相关标签:
1条回答
  • 2020-12-18 07:58

    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);
          }
        )
    }
    
    0 讨论(0)
提交回复
热议问题