【问题标题】:There is a way to avoid navigator.geolocation.getCurrentPosition from be cached?有没有办法避免 navigator.geolocation.getCurrentPosition 被缓存?
【发布时间】:2019-08-26 11:19:19
【问题描述】:

我在我的 React Native 应用程序中使用 navigator.geolocation.getCurrentPosition() 函数来获取我的设备的位置,但我一直在阅读,有时如果该函数指出您没有良好的信号,它可能会返回缓存的位置。有没有办法避免返回缓存位置而返回错误?

【问题讨论】:

    标签: javascript react-native caching location


    【解决方案1】:

    geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]);

    在函数中使用选项值。你可以使用maximumAge

    • maximumAge(ms)-代表最大寿命的正值 可逆缓存位置的毫秒数。如果设置为 0,则表示 设备不能使用缓存的位置,必须实际 检索当前位置。当设置为Infinity时,设备 总是返回一个缓存的位置,不管它的生命周期。这 默认为INFINITY
    var options = {
      enableHighAccuracy: true, // true: use GPS false : WIFI 
      maximumAge: 0 // default Infinity
    };
    
    function success(pos) {
      var crd = pos.coords;
    
      console.log('Your current position is:');
      console.log('Latitude : ' + crd.latitude);
      console.log('Longitude: ' + crd.longitude);
      console.log('More or less ' + crd.accuracy + ' meters.');
    };
    
    function error(err) {
      console.warn('ERROR(' + err.code + '): ' + err.message);
    };
    
    

    【讨论】:

    • 它没有解决问题。虽然你说的是对的,但我也在做同样的事情并且没有工作。我找到了关键,除了 maxAge 之外,我还必须添加超时时间,因为如果我不这样做,设备将无法在没有年龄的情况下获得正确的位置。出于这个原因,我不得不设置 maximumAge = 0 和超时 15000。无论如何感谢您的回复!
    【解决方案2】:

    我找到了解决办法!

    问题是我没有将超时时间传递给选项,然后设备试图立即获取位置,所以它无法做到这一点,而是从缓存中获取。

    现在获取位置大约需要 3 秒,但工作正常!

    【讨论】:

      【解决方案3】:

      我有类似的问题。 第一个位置从 navigator.geolocation.watchPosition(onLocationFound, onLocationError, {maximumAge:60000, timeout:12000, enableHighAccuracy:true}); 太老了。 比较 e.timestamp 和当前时间戳

      now = new Date(); 
      if((now - e.timestamp)<10000){ //OK if less than 10 sek (10000ms) 
      //YES, new location
      //stop updating navigator.geolocation.clearWatch(window.watchId);
      }
      else
      { 
      //old lacation, wait 
      }
      

      【讨论】:

        猜你喜欢
        • 2014-11-17
        • 2019-09-07
        • 1970-01-01
        • 2019-05-29
        • 2011-09-13
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        相关资源
        最近更新 更多