Categories
Internet

Exploring the HTML5 Geolocation API Part II

This is a part of HTML5 series. In case you didn’t read it, I suggest you go through this first, or else this will look like wtf!!!
Have a look here.

All right. Now what did we do?

window.onload = getMyLocation;

Here you are just calling the function getMyLocation as soon as the browser loads the page.

In function getMyLocation(), we simply check if geolocation is supported by the web browser.

If navigator.geolocation object exists then you can get the current position by calling this;
navigator.geolocation.getCurrentPosition(displayLocation);

displayLocation is another function.

If geolocation is not found, an alert is shown.

In the displayLocation function, the latitude and longitude of your current location is recorded and the DOM is accordingly modified.
Basically that’s it. If you give the the browser the permission to track your location, your location will be shown.
A number of errors can happen though.
o Unknown error – Bad luck, I have no clue about it
o Permission denied by user – If you do not allow the browser to track your location
o Location is not available – If none of the processes to find out your location works
o Request Timed Out – If the browser waits too long for the results to come

Fortunately you can handle this error quite easily. Add this code to the javascript file you created before.

function displayError(error) {
    var errorTypes = {
        0: "Unknown error",
        1: "Permission denied",
        2: "Position is not available",
        3: "Request timeout"
    };
    var errorMessage = errorTypes[error.code];
    if (error.code == 0 || error.code == 2) {
        errorMessage = errorMessage + "" + error.message;
    }
    var div = document.getElementById("location");
    div.innerHTML = errorMessage;
}

That’s it then. That’s all. Be sure to subscribe and like us on facebook. see ya.


By Sarthak Ganguly

A programming aficionado, Sarthak spends most of his time programming or computing. He has been programming since his sixth grade. Now he has two websites in his name and is busy writing two books. Apart from programming, he likes reading books, hanging out with friends, watching movies and planning wartime strategies.

Leave a Reply

Your email address will not be published. Required fields are marked *