【问题标题】:navigator.geolocation.watchPosition just not workingnavigator.geolocation.watchPosition 只是不工作
【发布时间】:2012-11-16 16:08:39
【问题描述】:

好的,我的代码在下面,所以我将解释我在做什么以及我得到的结果。

我正在尝试使用 navigator.geolocation.watchPosition 获取用户位置。我已经指定了成功和错误回调。我第一次获得位置时通常非常不准确,因此我使用 watchPosition 继续获得位置,直到尝试 4 次或获得准确到 500 米以内的位置。

我遇到的问题:

  • 它永远不会进入 android 的错误回调(在 HTC 上测试 感觉和三星 Galaxy S3)。然而,在 iPhone 上,它似乎 超过 50% 的时间输入错误回调。

  • 它也永远不会超时。它只是不断搜索,直到收到 位置。

  • 检索位置需要 0-60 秒。有时它在页面加载完成之前就有它,有时它需要一分钟的大部分时间。也没有可辨别的模式来解释为什么它有时会很快,而其他时候为什么不能。

我搜索了许多论坛帖子和许多 stackoverflow 问题以及地理位置规范和任何其他文档。关于它的信息并不多,更不用说这些问题了。有什么我做错了吗?或者这只是与位置合作的本质?

if(navigator.geolocation){
        var geo_count = 0;

        var wpid = navigator.geolocation.watchPosition(success, error, {
            enableHighAccuracy: true, 
            maximumAge: 0, 
            timeout: 10000
        });

        function success(position){
            alert(position.coords.accuracy)

            geo_count = geo_count + 1;

            if(position.coords.latitude && position.coords.longitude && position.coords.accuracy < 500){
                navigator.geolocation.clearWatch(wpid); 

                alert('position obtained!');    
            }
            else if(geo_count > 4){
                navigator.geolocation.clearWatch(wpid);

                alert('inaccurate position obtained');
            }
        }

        function error(error){
            switch(error.code){
                case 1:
                    alert('permission denied');
                    break;
                case 2:
                    alert('position unavailable');
                    break;
                case 3:
                    alert('timeout');
                    break;
                default:
                    alert('unknown error');
                    break;
            }
        }
    }

【问题讨论】:

    标签: javascript geolocation w3c-geolocation


    【解决方案1】:

    我建议检查使用:

    if (typeof navigator.geolocation === 'object' && typeof navigator.geolocation.watchPosition === 'function') {
        ...
    }
    

    “Geolocation.watchPosition() 方法用于注册一个处理函数,该处理函数将在每次设备位置发生变化时自动调用。您还可以选择指定错误处理回调函数。”

    可能它不会触发,因为位置仍然相同? ^^

    尝试使用带有 Interval 或 Webworker 的 Geolocation.getCurrentPosition() 对其进行调试:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation

    祝你好运

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-07
      • 2017-11-04
      • 2018-04-20
      • 2013-05-08
      • 2010-09-30
      • 2023-03-13
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多