Sunday, December 26, 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:
  • 3: TIMEOUT
The message property returns a string describing what went wrong. Be careful, this property is primarily intended for debugging!


The codesnippet below only shows the part where I am handling the PositionErrorCallback. You can find the demo and full source here.

function onError(error){
    var content = document.getElementById("content");        
    var message = "";
    switch (error.code) {
        case 0:
            message = "Something went wrong: " + error.message;
        case 1:
            message = "You denied permission to this page to retrieve a location.";
        case 2:
            message = "The browser was unable to determine a location: " + error.message;
        case 3:
            message = "The browser timed out before retrieving the location.";
    content.innerHTML = message;

No comments:

Post a Comment