I'm using the getCurrentPosition method in Javascript. I would like to implement a button that stops the execution of the method "getCurrentPosition" when it's clicked. I tried with throw/try/catch blocks but it doesn't seem to work :
try { $('#cancel').on("click", function() { $.mobile.loading('hide'); throw "stop"; }); navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy: true, timeout : 30000 }); } catch ( er ) { alert(er); return false; }
Any ideas? Is it even possible in JS ? I had an idea but I don't know if it's possible to trigger a timeout with a JS method so that the getCurrentPosition breaks ?
I'm using the getCurrentPosition method in Javascript. I would like to implement a button that stops the execution of the method "getCurrentPosition" when it's clicked. I tried with throw/try/catch blocks but it doesn't seem to work :
try { $('#cancel').on("click", function() { $.mobile.loading('hide'); throw "stop"; }); navigator.geolocation.getCurrentPosition(foundLocation, noLocation, {enableHighAccuracy: true, timeout : 30000 }); } catch ( er ) { alert(er); return false; }
Any ideas? Is it even possible in JS ? I had an idea but I don't know if it's possible to trigger a timeout with a JS method so that the getCurrentPosition breaks ?
Share Improve this question edited Apr 16, 2013 at 20:02 Gajotres 57.3k16 gold badges105 silver badges131 bronze badges asked Apr 11, 2013 at 14:50 LailaLaila 1,5113 gold badges14 silver badges28 bronze badges 2- It's supposed to be an asynchronous method so shouldn't stop rendering or anything but the w3 spec doesn't allow you to stop it once started. Do you just want to ignore the result if the button is clicked? The code you posted has no chance of working, events and asynch methods do not work that way. – mattmanser Commented Apr 11, 2013 at 15:16
- When the button is clicked, I want to stop the execution of getCurrentPosition (with something similar to clearTimeout). – Laila Commented Apr 11, 2013 at 15:20
1 Answer
Reset to default 17Solution:
Method navigator.geolocation.getCurrentPosition is an asynchronous function so don't count on stopping it just like that.
You should instead use other function called: navigator.geolocation.watchPosition. It works in the same way as getCurrentPosition but what make it usefull in your case is another function called navigator.geolocation.clearWatch and that function is used to stop watchPosition.
Example:
geoLoc = navigator.geolocation;
watchID = geoLoc.watchPosition(showLocation, errorHandler, options);
geoLoc.clearWatch(watchID);