【问题标题】:How do I get Geolocation watchPosition to run until I get an accurate result?在获得准确结果之前,如何让 Geolocation watchPosition 运行?
【发布时间】:2016-10-11 21:43:57
【问题描述】:

我一直在使用地理定位navigator.geolocation.getCurrentPosition,但发现它不如navigator.geolocation.watchPosition 准确。所以我的想法是让navigator.geolocation.watchPosition运行,直到它得到<=100的准确度,然后显示位置,如果在15秒内失败则显示错误。

这是我得到的:

function getLocation() {
    if (navigator.geolocation) {
        var geo_options = {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 0
        };
        var watchID = navigator.geolocation.watchPosition(
            showPosition,
            showError,
            geo_options
        );
    } else {
        // Error here. Geolocation disabled.
    }
}

function showPosition(position) {
    if (position.coords.accuracy > 100) {
        // Keep trying
    } else {
        // Fire up the map, we got a position!
        // Clear the watchID.
        navigator.geolocation.clearWatch(watchID);
    }
}

我的问题是由于某种原因我无法清除成功的 watchID,因为它说它是未定义的。我猜那是因为函数在外面。

是否有一种简单的方法可以做到这一点,以便仅在准确度低于 100 时触发showPosition?现在showPosition 随时被触发,因为它在watchPosition 函数内。

【问题讨论】:

    标签: javascript jquery geolocation


    【解决方案1】:

    那是因为watchID undefined。您已经在getLocation 的范围内定义了它,它不与showPosition 共享其范围。尝试在它们之外声明它。

    var watchID;
    
    function getLocation() {
      ...
      watchID = navigator.geolocation.watchPosition(showPosition, showError, geo_options);
    }
    
    function showPosition(position) {
      if (position.coords.accuracy <= 100) {
        navigator.geolocation.clearWatch(watchID);
      }
    }
    

    专业提示:如果您的代码在 strict mode 中运行,它会提醒您注意此错误。

    'use strict';
    
    function declareX() {
      var x = 1;
    }
    
    function useX() {
      console.log(x);
    }
    
    declareX();
    useX();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 2014-05-12
      • 2013-09-06
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      相关资源
      最近更新 更多