There is a way to avoid navigator.geolocation.getCurrentPosition from be cached?

那年仲夏 提交于 2019-12-13 03:48:31

问题


I'm using in my React Native App the navigator.geolocation.getCurrentPosition() function to get the location of my device but I have been reading that sometimes if the function notes that you have no good signal it could return the cached location. There is a way to avoid the returning cached location and return an error instead?


回答1:


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

Use the option value in the function. You can use maximumAge

  • maximumAge(ms)-positive value representing the maximum life in milliseconds of a reversible cache location. If set to 0, it means that the device cannot use the cached location and must actually retrieve the current location. When set to Infinity, the device always returns a cached position, regardless of its lifetime. The default is 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);
};




回答2:


I found the solution!

The problem was that I wasn't passing the timeout time to the options and then the device was trying to get the location immediately, so it wouldn't be able to do that and was getting from the cache.

Now it is getting like 3 seconds to get the location but works fine!




回答3:


I had similar problem. First location from navigator.geolocation.watchPosition(onLocationFound, onLocationError, {maximumAge:60000, timeout:12000, enableHighAccuracy:true}); was to old. Compare e.timestamp and current 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 
}


来源:https://stackoverflow.com/questions/57656908/there-is-a-way-to-avoid-navigator-geolocation-getcurrentposition-from-be-cached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!