有一种方法可以避免navigator.geolocation.getCurrentPosition被缓存?

时间:2019-08-26 11:19:19

标签: javascript react-native caching location

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

3 个答案:

答案 0 :(得分: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);
};

答案 1 :(得分:0)

我找到了解决方法!

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

现在大约需要3秒钟才能找到位置,但是效果很好!

答案 2 :(得分:0)

我有类似的问题。 来自的第一个位置 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 
}