JS Geolocation 等到成功再返回值 [英] JS Geolocation wait until success before return value

查看:20
本文介绍了JS Geolocation 等到成功再返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于JS Geolocation 等到成功再返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆