Reputation: 2047
I am using navigator.geolocation.getCurrentPosition()
to get current location in mobile app.
At first it's getting current location correctly.
I am calling the function every second to keep location values(latitude, longitude) updated.
But each time I call the function it's returning same values and the timestamp
is not changing as well.
Any ideas?
Upvotes: 4
Views: 4135
Reputation: 1
On my environment, value 0 was treated as infinity
. (I am using react-native)
So, I needed to change from maximumAge: 0
to maximumAge: 1
.
Then I could get correct current position every time.
Upvotes: 0
Reputation: 115
You should consider using the parameter 'maximumAge' and set it to 0 to avoid getting cached values. e.g.
navigator.geolocation.getCurrentPosition(position => {
region: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
}, err => {
console.log(err)
alert('fetching the position failed')
}, {enableHighAccuracy: false, timeout: 20000, maximumAge: 0})
As per MDN documentation :
The PositionOptions.maximumAge property is a positive long value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to 0, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set to Infinity the device must return a cached position regardless of its age.
Upvotes: 1
Reputation: 1609
You can pass additional options to getCurrentPosition()
.
Supported options are timeout (ms), maximumAge (ms), enableHighAccuracy (bool)
.
Here you can see the maximumAge option. It will return the cached location data if there is a cached location within the maximumAge limit. You can set it to 0, so it will not return any cached data, instead read and return location data everytime you make a location request.
Also I am not sure if you will get updated location every second, it is an async task and sometimes longer than one second to complete the whole request > read location > send back response
process. You'll have to keep this in mind too.
Upvotes: 0