Jef Claes

On software and life

26 Dec 2010

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:

  1. PERMISSION_DENIED
  2. POSITION_UNAVAILABLE
  3. 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;
}