HTML 5 GeoLocation Example

In this blog, I will try to create a simple sample which uses the new geo location feature of HTML5. Read on -
The HTML5 geo location feature is very simple to use. In a nutshell, you call a method which returns a position object. This position object contains the position information such as 
  • lattitude
  • longitude
  • accuracy (in metres)
  • altitude
  • altitude accuracy (in metres)
  • heading - direction in which you are moving
  • speed - speed with which you are moving
The sample code below shows how this method is called and how the values are populated in simple text boxes.
    $('#btnGeoLoc').click(function () {
        navigator.geolocation.getCurrentPosition(function (position) {

            $('#viewMap').attr("href", "" +
                    $('#lat').val() + ",+" + $('#long').val() +

        function () {
            alert("Error occurred");
Here, I am showing the code where there is a button on whose click I use some jQuery events to populate the textboxes. In the end, I enable a "view map" anchor tag with a link to google maps by using the latitude and longitude that we just obtained.
The getCurrentPosition method takes 2 arguments. Both are functions. The first one will get if the call is successful and the second one will get called if there was an error. We can then go through the error code to see what kind of error occurred and take subsequent action.
In this example, we used the getCurrentPosition() method. This method is used to get the position once. If you want to continuously monitor your position, you can use the watchPosition() method.

No comments: