JS Geolocation在返回值之前等到成功

Gus*_*ooL 5 javascript geolocation

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

我的脚本示例:

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}
        )
    }
Run Code Online (Sandbox Code Playgroud)

如果我们执行此脚本updateCoordinate,该函数将返回undefined.但过了一会儿,如果我们检查一下它,就会设置好坐标.

如何使getCurrentPosition等到返回值之前得到精确的坐标?

And*_*ndy 14

使用回调,而不是超时,这将导致各种各样的问题.有点像:

// 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);
      }
    )
}
Run Code Online (Sandbox Code Playgroud)

  • 它不起作用! (2认同)