Adding HTML5 Geolocation to your web applications

One of the interesting and useful addition to the HTML5 specification is the Geolocation API. The Geolocation API allows users to share their location with web applications so that they can enjoy the benefits of various location-aware services.

Geolocation enables you as a developer or website owner to figure out where a particular user is located on the planet. This can be helpful in various web applications; for example in social networking, where you can find out where your various friends are currently located or in advertising where you can display targeted ads based on the users location.

Getting your users location

In the past, IP based geolocation was the only way to get a users possible location. Services and databases such as MaxMind or ip2location where used to locate the position of the user, based on the users IP address.

Now that Geolocation is available as a built-in API service in HTML5, it makes easier for developers to quickly integrate location based services into their applications.

Detecting Geolocation support

Before you write any Geolocation code you need to check if it is supported on your browser. The simplest way to detect if Geolocation is supported is to use the global ‘navigator’ object.

if(navigator.geolocation) {
    // Geolocation supported. Do something here.
}

Reading users location

Once we have checked that Geolocation is supported we can use the following to get the users location data.

navigator.geolocation.getCurrentPosition(success_handler, error_handler);

This will execute the callback function ‘success_handler’ if the request is successful or the ‘error_handler’ callback if some error occurs. The location data is available as a ‘position’ object in the ‘success_handler’.

function success_handler(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        accuracy = position.coords.accuracy;
    }

Below is a list of all properties available:

Property Data Type Unit
coords.latitude double decimal degrees
coords.longitude double decimal degrees
coords.altitude meters decimal degrees
coords.accuracy double meters
coords.altitudeAccuracy double or null meters
coords.heading double or null degrees
coords.speed double or null meters/second
timestamp DOMTimeStamp Date() object

User privacy

When you opened the demo web page given above you may have received a notification bar like the following; this bar requests your permission to share your location with the browser.

The HTML5 Geolocation specification mandates that before any location data can be retrieved the browser first request permission from the user to share its location. Only when the user allows does the browser retrieves the users location.

Note: If opted to ‘always share’ or ‘always deny’ in Firefox and later change your mind, you can easily revert permissions by going back to the website and selecting ‘Tools’ menu->’Page Info’ in Firefox. Then change the setting for ‘Share Location’ on the Permissions tab.

How does Geolocation work

Once you give permission to the browser to share your location, the browser gathers information about nearby access points and also your computer’s IP address which the browser then sends to the default geolocation service provider – Google Location Services in case of Firefox, to get an estimate of your location. This location estimate is then sent to the requesting website.

Location accuracy

You may have noticed above that the ‘position’ object returns a accuracy variable. accuracy represents a value in meters which specifies how close the latitude and longitude values are to the actual location. You can increase the location accuracy by passing a option to the getCurrentPosition function. Bear in mind that this is only a hint that you give to the browser; whether it returns a high accuracy result depends on the location service your browser uses.

navigator.geolocation.getCurrentPosition(
                                    success_handler, 
                                    error_handler, 
                                    {enableHighAccuracy:true});

Saving location to Cookies

Once we get the location data from the user it is better to store it for the entire session so we can use it on other pages. Storing it in cookies is one quick option. For this example I’ve used the jQuery cookie plugin, which provides a simple and clean way to save and retrieve cookies.

We can store the cookies in the ‘success_handler’ and then later check the same before issuing another location request.

function success_handler(position) {
        /* Get the location data */
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        accuracy = position.coords.accuracy;
 
        $.cookie("posLat", latitude);
        $.cookie("posLon", longitude);
        $.cookie("posAccuracy", accuracy);
    }

Now that we have nicely saved the data, all the other site pages can now access the location data by reading them from the cookies.

/* Check if location data is available in the cookies */
if($.cookie("posLat")) {
    latitude  = $.cookie("posLat");
    longitude = $.cookie("posLon");
    accuracy  = $.cookie("posAccuracy");
 
    // do something here
}

Continuous Position Updates

In the above example the location was read once and stored for future use. But what if your application is on a mobile device and you are on the move. The Geolocation API provides another function navigator.geolocation.watchPosition that automatically retrieves the users current location if it ever changes. The function is similar to ‘getCurrentPosition’, the only difference is that it regularly polls the location and returns the new location data.

var watch_id = navigator.geolocation.watchPosition(
                                        success_handler, 
                                        error_handler
                                        );

The function return a unique numeric id which you can later use to stop the polling.

navigator.geolocation.clearWatch(watch_id);


11 thoughts on “Adding HTML5 Geolocation to your web applications

  1. Nice write up… covering almost all the geoloc capabilities in html5. One could directly read the html5 geolocation spec next.
    Few points:
    Would be good to use local storage instead of cookies.
    Also, a table highlighting current browser support for geolocation would be a good add to this article.
    One could also check out Modernizr for browser capability detection.

  2. hi there, help me please..
    i already get lat and long, i already put it in cookie
    now i want to use that cookies in php page, how to fetch the cookies and store it to php variable

  3. your error_handler does not detect the user choice of “Not now” or clicking the X in the corner of the Share Location (Always/Never) popup.

    not sure why, but its interesting to try to solve this minor issue :-)

  4. Hi Sameer,

    First of all ,Thanks for the brilliant article.
    One question:

    All browsers prompt me to “allow” or “deny” access to current location.

    How can i disable “Allow” or “Deny” prompts/alerts in the beginning ?
    I have a page and want to allow visitors to see their current location by default.

    I would appreciate your help in this regard.

  5. The confirmation dialog is to prevent websites from accessing data without the user being aware of it. As far as I know you can’t bypass it from your website, which actually is a good thing for security reasons.

Comments are closed.