How to Use Geolocation to Locate Your Visitors

With the increasing popularity of mobile devices such as smartphones and the iPad, location-aware applications are flourishing. On the other hand, with HTML5 and all of its amazing features, web applications seem to be the way to go. So, how exactly do you locate your web application visitors? Let’s start with a little background information on geolocation.

Positioning Methods

You are hereThere are a few methods that can be used to find someone’s position. The first and least accurate one is IP location. It checks the user’s IP address against a database to find the location, which is usually the name of the city or region. Though not very accurate, it has been widely used for a while and has the benefit of being the only method you can use server-side.

The second method is specific to mobile phones (and other devices connecting to mobile networks). It calculates the approximate location by figuring out your approximate distance to cell antennas around you (according to the signal power). The accuracy varies depending on the density of antennas and is therefore more accurate in urban areas.

Another method uses Wi-Fi and can therefore work with most mobile devices, including laptops. It works kind of the same as the cell antennas method, but uses Wi-Fi access point and a huge database of their known location. Since the range of Wi-Fi is pretty limited and there can potentially be dozens of known access points around you, the accuracy is actually quite impressive. Of course though, it works only if you are within range of at least one known access point. In urban areas, this is likely, but outside the city, you may be out of luck.

The most accurate method is GPS, which most modern mobile phones are capable of using. It uses signals from satellites all around the globe to calculate the exact location. Though incredibly accurate (down to a few meters), it has some limitations. First, it tends to consume a fair amount of energy, so many people may usually keep it off on their phone. Also, it works well only in open spaces, where the sky is visible. It is inaccurate or unusable indoors and when near large buildings. To help, hybrid implementations of GPS and other methods are often used. So if GPS fails, maybe Wi-Fi or cell antennas will work.

Enough background data! How do you code it?

Google Gears and W3C Geolocation API

In 2008, Google added the Geolocation API to Gears, a plug-in that extends browsers capabilities. It was now possible with a few lines of javascript to find the user’s location. Last year, the W3C released its Geolocation API specifications. In the past months, it has been implemented in the main browsers, but is not yet supported by all. It is meant to eventually completely replace Gears’ API, but for now it’s a good thing to have both.

Fortunately, though the implementations aren’t exactly the same, they are a lot alike. Also, you don’t have to care about what method it uses to find the location, nor on what kind of device your application is used. All you have to check for is if W3C geolocation is supported and/or if Gears is installed. Now, let’s code!

The Code

First, we need some simple HTML. The W3C geolocation, if supported, is natively implemented by the browser, so it doesn’t require to include any external javascript. Gears however, requires to add the gears_init.js file which you can download here. Since we’ll also be using the Google Maps API, we’ll also include its library.


<script type="text/javascript" src="gears_init.js"></script>

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

Now, for the sake of this example, we are simply going to display a Google map of the location once it’s found. To do so, we’ll need to add a container in the body, with some text in it that will appear until the map is loaded:

<div id="TheMap">Finding your location...</div>

That’s all for the HTML. Now let’s add some javascript. Finding the location can take a few seconds, so this call is made asynchronously. This means that we need to create a callback function that will receive the position information. Here’s a little function that will display this on a map, also showing the accuracy:


/* Show the position on a map */
function showPosition(position) {
 var location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
 var options = { center: location,
                 mapTypeId: google.maps.MapTypeId.HYBRID };
 var map = new google.maps.Map(document.getElementById('TheMap'), options);
 var circleOptions = { map: map,
                       center: location,
                       radius: position.coords.accuracy,
                       fillColor: '#0055ff',
                       fillOpacity: 0.2,
                       strokeColor: '#0055ff',
                       strokeWeight: 1,
                       strokeOpacity: 0.7 };
 var circle = new google.maps.Circle(circleOptions);
 map.fitBounds(circle.getBounds());
}

I won’t explain here how the Google Maps API works since it is not the point of this article. If you want more info about it, please check the documentation. Note that we receive a position object. This can be either the W3C or the Gears objects, which are slightly different. However, they both have a “coords” property that contains the information we care about: latitude, longitude and accuracy (in meters).

It is also possible to create another callback function to process errors from the APIs. Let’s create a really simple one:


/* No location available */
function noLocation(err) {
 document.getElementById('TheMap').innerHTML = 'No location available';
}

An error object is received as a parameter which contains information about the error. Here we simply display a message in our container stating that no location information is available, but of course you could do much more.

Let’s now create the function that will actually do the call. First it needs to get an object either from the W3C API or from Gears. Then, using that object it can call one of two methods: getCurrentPosition and watchPosition. The first simply gets the position once and calls the callback function. The latter periodically retrieves the position and calls the callback method if the position changed significantly since the last time. Let’s make a function that will enable to do both depending on a parameter.

Also, since the call is asynchronous, we can’t use a try-catch block to catch any runtime error, so just in case something goes wrong, we’ll set a timeout that will call the error callback function if no location was found yet. There is actually a known issue with the current latest release of Firefox 3.6 when no Wi-Fi is available that will generate such a runtime error.


/* Timeout in case something goes wrong */
var locationTimeout = null;

/* Get the location */
function getLocation(watch) {
 var geo = null;

 if (navigator.geolocation) {  /* Check for W3C geolocation support */
   geo = navigator.geolocation;
 } else if (google.gears) {  /* Check for Google Gears */
   geo = google.gears.factory.create('beta.geolocation');
 }

 if (geo != null) {
   var geoTimeout = setTimeout(noLocation, 5000);

 if (watch) {  /* Watch for location */
   geo.watchPosition(function(position) { clearTimeout(geoTimeout); showPosition(position); }, noLocation);
 } else {  /* Get location once */
   geo.getCurrentPosition(function(position) { clearTimeout(geoTimeout); showPosition(position); }, noLocation);
 }

 } else {  /* Geolocation is not supported */
   noLocation();
 }
}

getLocation(false);

As you can see, we can test for W3C geolocation support by checking if navigator.geolocation is set and if Gears is installed by checking if google.gears is set. We can then set our geolocation object. If it’s not null (one of the method is supported), we then call one of the functions, depending on the value of the watch variable. Both methods take the success callback as the first parameter and the error callback as the second parameter. We use an anonymous function as the first parameter to clear the timeout before calling the success callback. If no geolocation method was supported, we simply call the error callback. Finally, we actually call the function requesting only to get the location once (false parameter).

You can see the final result on this demo page.

1 thought on “How to Use Geolocation to Locate Your Visitors”

  1. Hi Thanks for this. I’m working on an eCommerce site for a service selling local produce. The intention is to sell only to customers living locally. I’d like potential customer to be able to check whether they fall within the delivery are by displying their position and seeing whether it is inside the delivery area diplayed by a alrger circle. In essence I need to call in a custom Google Map with an area allready mapped out. Any ideas how this could be implemented. Thanks in advance.

Comments are closed.