I am a bit concerned about the safety of this code example in the W3C Geolocation spec:
// Forcing the user agent to return a fresh cached position.
// Request a position. We only accept cached positions whose age is not
// greater than 10 minutes. If the user agent does not have a fresh
// enough cached position object, it will immediately invoke the error
// callback.
navigator.geolocation.getCurrentPosition(successCallback,
errorCallback,
{maximumAge:600000, timeout:0});
function successCallback(position) {
// By using the 'maximumAge' option above, the position
// object is guaranteed to be at most 10 minutes old.
// By using a 'timeout' of 0 milliseconds, if there is
// no suitable cached position available, the user agent
// will aynchronously invoke the error callback with code
// TIMEOUT and will not initiate a new position
// acquisition process.
}
function errorCallback(error) {
switch(error.code) {
case error.TIMEOUT:
// Quick fallback when no suitable cached position exists.
doFallback();
// Acquire a new position object.
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
break;
case ... // treat the other error cases.
};
}
function doFallback() {
// No fresh enough cached position available.
// Fallback to a default position.
}
What happens if the browser genuinely can't return a location fix - for whatever reason - and keeps timing out?
Surely the code will end up in an infinite loop with errorCallback being called over and over again.
I see the doFallback() call but that won't stop errorCallback being called repeatedly. Or will it?
error.code will return POSITION_UNAVAILABLE. The code in the spec is an infinite loop because I guess it is exactly what they want. Imagine a scenario where you are in navigation mode, moving through space. Sometimes, you go through a tunnel and you lost the network and are unable to get any position for a certain amount of time that you do not control. Then when out of the tunnel, it is good to be able to get the position automatically. In a scenario, where you need a one time value, the piece of code will not be useful, but then easy to modify to stop with an error message.
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