With GPS chipsets x as well as modern webbrowsers present in most mobile devices (iPhone and Android Phones, Tablets and even Notebooks) these days, it is surely time to start using geolocation with your webservices.

This is actually quite simple, as most current browsers (this as always excludes internet explorer) implement the W3C Geolocation API Specification. As seen in many tutorials, you simple check if the navigator.geolocation object exists, call navigator.geolocation.getCurrentPosition(my_callback) and get the current location of your user.

Nice and easy, but there is one little Problem: on most devices, this can lead to very inaccurate results. For example the iPhone 3G often returns positions with 500m accuracy, even if you pass the enableHighAccuracy:true. So watching the current position until it’s accuracy stabilizes is inevitable if you want to serve your user with pleasing results. Also this enables you to add some nice ‘wait for it’ animation that shows the current degree of accuracy – as for example seen in the iPhone Maps Application.

Luckily the Geolocation API also specifies the watchLocation function. This one can be called like that: var watch_id = navigator.geolocation.watchPosition(your_callback). This way your callback gets called everytime the users position or the accuracy of the current position changes. Under good conditions it just takes a few seconds to reach good enough accuracy for your application. As soon as your callback gets a position with good enough accuracy, you should call navigator.geolocation.clearWatch(watch_id) to disable the GPS again. This is especially important on mobile devices where an always on GPS can drain the battery quite fast.

To ease the usage of the geolocation api, i wrote a simple javascript that tries to get the current users location for a specific accuracy threshold. It is as always available on github.

Using it is really easy. Simply call simple_locator with your callbacks and you are done. Check out this quick example:


  var locator_update = function(coords, location_name) {
    var output = document.getElementById('output');
    output.innerHTML = 'lat: ' + coords.latitude +
                                      '; lng: ' + coords.longitude +
                                      '; acc: ' + coords.accuracy +
                                     '' + location_name;
  };
  simple_locator({
    threshold:50,
    running_callback : locator_update,
    finished_callback : locator_update,
  });

As an additional tool i also added reverse geocoding via google maps api v3. Just include the google maps api, set the google_geolocation:true option and the second parameter of your callback will contain the address of the current location. An example can be found in the simple_locator.html file on github.