HTML5: Exception handling with the Geolocation API
In my previous post on the Geolocation API I passed in a PositionErrorCallback
to the geolocation.getCurrentPosition() method. When I received this callback I displayed a generic message informing the user something went wrong. In real-world scenarios you probably want the message to be more specific. You might also want to call a specific fallback method depending on what went wrong.
This is where the PositionError argument of the PositionErrorCallback
comes in handy. This object has two properties: code
and message
.
The code property can return three codes:
PERMISSION_DENIED
POSITION_UNAVAILABLE
TIMEOUT
The message property returns a string describing what went wrong. Be careful, this property is primarily intended for debugging!
Example
The codesnippet below only shows the part where I am handling the
PositionErrorCallback
.
function onError(error){
var content = document.getElementById("content");
var message = "";
switch (error.code) {
case 0:
message = "Something went wrong: " + error.message;
break;
case 1:
message = "You denied permission to this page to retrieve a location.";
break;
case 2:
message = "The browser was unable to determine a location: " + error.message;
break;
case 3:
message = "The browser timed out before retrieving the location.";
break;
}
content.innerHTML = message;
}