Warning message

  • The service having id "delicious" is missing, reactivate its module or save again the list of services.
  • The service having id "stumbleupon" is missing, reactivate its module or save again the list of services.
  • The service having id "linkedin" is missing, reactivate its module or save again the list of services.
  • The service having id "identica" is missing, reactivate its module or save again the list of services.
  • The service having id "diigo" is missing, reactivate its module or save again the list of services.
  • The service having id "twitter_widget" is missing, reactivate its module or save again the list of services.
  • The service having id "facebook_like" is missing, reactivate its module or save again the list of services.
  • The service having id "digg_smart_button" is missing, reactivate its module or save again the list of services.

Where are you? Find out with geolocation in Javascript.

Despite the idea of "being in Cyberspace" and the power of the Internet to connect us to people all over the world regardless of our location, we often use a browser to find out about people and services close to us. These might be queries such as finding the opening times of a local store, the time of a train or local expertise. Each time we do this it is often necessary to tell the website where we are, typcially by providing a post code, but what if you don't know the postcode? Fortunately browsers and becoming much more clever, and some can even work out where you are.

Since the arrival of Firefox 3.5, Mozilla have made available to developers functionality to find, with their consent, the location of the user. I've been meaning to look into this for a while, so I thought I'd have a look at the developer documentation to see how this works. Writing the code to use this functionity seemed straightforward enough, and I made a small code sample to demonstrate geolocation in action. Mozilla's implementation follows the first draft of the W3C's Geolocation API Specification, some other browsers follow this too so the good news if you want to wrote geolocation enabled web pages that work across different platforms.

If you use a device with built a built in GPS receiver it is often possible to pass the location from this to the geolocation functionality, but what if you are just using a desktop or laptop? Here comes the surprise, amazingly the location functionality may still work. Firefox can use Google Location Services to work out where you are based on your WiFi access point and IP address. When I tried this out I was amazed at how accurate it was, using a laptop with no GPS built in, the location was returned was actually in the next street! It also is possible to write providers for Firefox too to tell it a user's location.

There is of course a privacy implication here, and the data returned by the location service could be quite sensitive and also could be covered by data protection laws. If you want to find a location the user must explicitely agree to share it with your site. When you page loads and you ask for this information, a dialogue box will appear asking this permission. They might say no, so that is an error condition that has to be handled, the location might also be unavailable too. So below is my attempt at creating a self contained demonstration of this technology in action. You can save it to an html file on your machine or even put it on a web server to experiment. It doesn't do anything too exciting, just finds the longitude and latitude of the user and then uses these to construct a URL for Google Maps. This is shown to the user by replacing the contents of some tags on the page with updated information.

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation Demo</title>
  </head>
  <body>
    <h1>Geolocation Demo</h1>
    <p>Latitude: <span id="lat">0.00</span> Longitude: <span id="lon">0.00</span></p>
    <p><a id="gmaps_link" href="http://maps.google.co.uk/" target="_blank">View on Google Maps</a></p>

    <script language="javascript">
       // show the position on the page and make a google maps link
       function showPosition(position) {
         var lat = position.coords.latitude;
         var lon = position.coords.longitude;
         document.getElementById("lat").innerHTML = lat;
         document.getElementById("lon").innerHTML = lon;
         var gmaps_url = "http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=" + lat + "+" + lon;
         document.getElementById("gmaps_link").href = gmaps_url;
       }
       // report errors to user
       function errorHandler(error) {
         switch (error.code) {
          case error.PERMISSION_DENIED:
            alert("Could not get position as permission was denied.");
            break;
          case error.POSITION_UNAVAILABLE:
            alert("Could not get position as this information is not available at this time.");
            break;
           case error.TIMEOUT:
             alert("Attempt to get position timed out.");
            break;
           default:
            alert("Sorry, an error occurred. Code: " + error.code + " Message: " + error.message);
            break;
           }
       }
       // check browser can support geolocation, if so get the current position
       if (navigator.geolocation) {
         navigator.geolocation.getCurrentPosition(showPosition, errorHandler);
       }
       else {
         alert("Sorry, your browser does not support geolocation services.");
       }
    </script>
  </body>
</html>

On line 39 of the code you will see a line that says "if (navigator.geolocation)", this tests whether the browser being used has the geolocation functionality. If not an error message is shown. Adoption of this functionality is far from universal at the moment, I found this code sample works on Firefox 3.5, Firefox Mobile and MicroB on the Nokia N900 and the Apple iPhone. It did not work on IE7, Google Chrome or the G1 Android phone, which was a bit disappointing. If you try this out on other phones it would be great to hear from you.

The magic line to get the position is:
navigator.geolocation.getCurrentPosition(showPosition, errorHandler);

If all goes well a function called "showPostition" will be called with a Position object which will contain various information including the coordinates. Depending on the location provider more information might be available, including even an approximate postal address. This might be useful if you have an existing web application that takes a post code, with a few lines of javascript you could geolocation enable it! I haven't used this in the code sample here, so feel free to experiment with the code to find the extra information. The "errorHandler" function gets called if things go wrong. You will see in the sample a bit of code to just show the user what happened, but you could elaborate on this to provide an alternative course of action in your application, such as providing the location manually.

This could be really handy for mobile devices as you could write location aware applications that run server side, potentially saving the effort and expense of writing different applications for each platform. As it works on desktops too it could be used to enhance the experience of using many websites used to find local information. Of course it might take some getting used to, so if I was implementing this on a website I think I'd be careful about making sure users know what is going on and that they are in control of it.

Thanks to Doug Clow and Georgina Parsons for helping with the testing of the code sample.

References:

Comments

Interesting article, guessing geolocation is also a feature of Firefox 3.6 also?

That's right, Firefox 3.6 also introduced support for GPSD on Linux systems.

Hello,
I would like to know you are the Liam Green-Hughes from Castletown on the Isle of man !!!
If yes, I am not sure you'll remember me, I was a French teaching assistant from Brittany wher you cam once .

Add new comment

Comments are always very welcome, but please note the following:
  • Sadly due to the high number of spam comments recently all comments are now manually moderated. You comment will therefore not appear on the site instantly.
  • Comments on this web site are monitored for spam using Mollom. By posting a comment, you accept that your message and other personal details about you will be analysed and stored for anti-spam and quality monitoring purposes, in accordance with Mollom's privacy policy.
  • Please use your own name not a company or website name to submit comments. Your comment will be removed if you don't do this.
  • All links in comments will be marked with a no follow attribute. That means posting a link to your site here won't help your search engine rankings.
  • By submitting a comment you agree that your comment can be reproduced under the same licensing terms as the rest of the content on the site.
  • Comments can be removed at any time without explanation, but won't be removed just because you disagreed with something I said.