I'm encountering some issues with JavaScript's watchPosition and clearWatch functions that I don't quite understand, would appreciate it if someone could help out.
First off, the function in question...
function location(x){
var getLocation;
var lat_input = $(x).find(".latitude");
var lon_input = $(x).find(".longitude");
var acc_input = $(x).find(".accuracy");
function showPosition(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
accuracy = position.coords.accuracy;
$(lat_input).val(latitude);
$(lon_input).val(longitude);
$(acc_input).val(accuracy);
setTimeout(function(){
navigator.geolocation.clearWatch(getLocation);
alert('done');
}, 10000);
};
getLocation = navigator.geolocation.watchPosition(showPosition, null, {maximumAge: 0, timeout: Infinity, enableHighAccuracy: true});
};
In particular, my problem is with the code in the setTimeout section.
When I run this function on my laptop, everything starts out ok - the .longitude, .latitude, and .accuracy fields are populated accordingly. After 10 seconds, setTimeout is triggered - I can't say if clearWatch runs successfully (since the computer is pretty limited in its ability to find itself), but the odd behavior that I note here is that alert('done') is triggered twice.
When I run this function on my phone (the intended platform), everything gets off to a similarly good start, but after 10 seconds, alert('done') starts triggering endlessly, sometimes in immediate succession, sometimes with a few seconds in between. Most distressing, however, is that clearWatch doesn't appear to run at all - that lat, long, and accuracy fields continuously update after the 10 second mark.
If anyone can see what I am doing wrong here, your guidance would be much appreciated.
I hit a similar issue. I found the following code did not stop the watch:
navigator.geolocation.clearWatch(locationID);
STEP 1: Create a variable and assign it to navigator.geolocation
var geoLoc = navigator.geolocation;
var geoWatchID = geoLoc.watchPosition(
onGPSSuccess, onGPSError,
{ maximumAge: 300, timeout: 1500, enableHighAccuracy: true });
STEP 2: Stop Watch use the var geoloc not navigator.geolocation.clearWatch()
geoLoc.clearWatch(geoWatchID);
geoWatchID = null;
See http://www.tutorialspoint.com/html5/geolocation_clearwatch.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With