There is a way to avoid navigator.geolocation.getC

2019-08-31 02:16发布

问题:

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!