【发布时间】:2019-08-26 11:19:19
【问题描述】:
我在我的 React Native 应用程序中使用 navigator.geolocation.getCurrentPosition() 函数来获取我的设备的位置,但我一直在阅读,有时如果该函数指出您没有良好的信号,它可能会返回缓存的位置。有没有办法避免返回缓存位置而返回错误?
【问题讨论】:
标签: javascript react-native caching location
我在我的 React Native 应用程序中使用 navigator.geolocation.getCurrentPosition() 函数来获取我的设备的位置,但我一直在阅读,有时如果该函数指出您没有良好的信号,它可能会返回缓存的位置。有没有办法避免返回缓存位置而返回错误?
【问题讨论】:
标签: javascript react-native caching location
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);
};
【讨论】:
我找到了解决办法!
问题是我没有将超时时间传递给选项,然后设备试图立即获取位置,所以它无法做到这一点,而是从缓存中获取。
现在获取位置大约需要 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
}
【讨论】: