We're using navigator.geolocation.getCurrentPosition()
to get the user's current location. That function takes three parameters:
- a callback function to execute if it successfully gets the user's position
- an optional callback function to execute if it's unsuccessful
- optional settings
If the user has turned off location sharing on their mobile device (or in their desktop browser), the second callback function will be executed.
In that case, we give the user an alert message asking them to enable location sharing.
The problem we're finding is that if they then go and do that, then come back to the website and try clicking the link again, the browser seems to have cached the result from getCurrentPosition()
, and it executes the second callback again.
If they refresh the web page after updating their location settings, then it's fine. However I'm not sure we can detect when they've re-enabled their location sharing?
Is there any work-around here where we prevent getCurrentPosition()
from caching the unsuccessful response? Perhaps using I also tried using watchPosition, but that has the same problem; it doesn't automatically update when the user updates their location sharing settings.watchPosition()
?
<a href="" id="clickme">Click Me</a>
$(document).ready(function() {
$('#clickme').on('click', function() {
navigator.geolocation.getCurrentPosition(
function() {
console.log('success');
},
function(error) {
alert('you should enable location sharing');
console.log('failure');
},
{
timeout: 5000,
maximumAge: 0,
enableHighAccuracy: false
}
);
return false;
});
});
You can see this code in action on JSFiddle here.
- Disable location sharing, click Run, then click 'Click Me'. You should get the alert message and the failure response.
- Enable location sharing, then click 'Click Me' (without refreshing the page and without clicking Run again). You will still get the alert message.
- Refresh the page, and this time you'll get the success response.