Reputation: 46778
I am using the HTML5 geolocation API. I recently decided to shift from polling user position to using the watchPosition method, which is supposed to fire its "success" function, once the device position changes.
But instead, it is filling up my database with the same position over and over again. Relevant code posted below:
updateLocation = navigator.geolocation.watchPosition(success, failed, {enableHighAccuracy:true, maximumAge:30000, timeout:27000});
function success(){
showGPS(position);
}
function showGPS(position) {
var lng = position.coords.longitude;
var lat = position.coords.latitude;
gpsText.innerText = "Latitude: "+ lat +"\nLongitude: "+ lng + "\nAccuracy: "+ position.coords.accuracy + "\nSpeed:" + (position.coords.speed*3.6) + "\nAltitude:" + position.coords.altitude;
getData("http://databaseEntryURL/gpsReceiver.aspx?string=" + gpsText.innerText);
}
The getData gets called about 5 times a second. I'm sure the latlng is not changing. I'm using android 2.2, to load this page. How do i make it call the success function ONLY if the device position changes?
Upvotes: 0
Views: 5125
Reputation: 1
A more efficient way would be to set the watchPosition
as a variable and call clearWatch()
on it once you've received the first response:
var watchID = navigator.geolocation.watchPosition(onSuccess, onFailed);
function onSuccess(position) {
navigator.geolocation.clearWatch(watchID);
};
Upvotes: 0
Reputation: 2425
Maybe it's just caused by some bug, so even when the location has no change (or the change is so small) your callback is still triggered.
One way to solve it is storing the last location and using it to compare with the current location. If there's no change (or the change is too small), do nothing in the callback. This will save you bandwidth and database space.
If you need to save battery life for the phone then you need to optimize the options, for example, changing enableHighAccuracy
to false
.
Upvotes: 1