JS Geolocation 等到成功再返回值

2022-01-14 00:00:00 geolocation javascript

我尝试开发浏览器地理定位,但似乎地理定位在仍在搜索我的位置时会很快返回一个值.

I tried developing browser geolocation, but it seems geolocation quickly return a value when it is still searching for my location.

我的脚本示例:

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

如果我们执行这个脚本updateCoordinate,函数会返回undefined.但过了一会儿,如果我们检查 cookie,它会正确设置坐标.

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.

如何让getCurrentPosition等到获得精确坐标后再返回值?

How to make getCurrentPosition waiting until get exact coordinate before returning the value?

推荐答案

使用回调,而不是超时,这会让你遇到各种各样的问题.大致如下:

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

相关文章