Localize the user with the javascript Geolocation API


Javascript provides a function to get the location of the current user of your web page. Currently it is only implementend in Firefox 3.5 and Safari mobile version. Also Chrome has implemented it, but it isn’t turned on by default. I’m talking about the Geolocation API which is a W3C standard. It is amazing how accurate it works (in Switzerland). It normally localizes me with a 50 meters difference (about 150 feet). I build a simple web application which localizes you and show the result on Google maps (already said, only works with Firefox 3.5 currently). It would be great if you could post how accurate it is in your country!

The Geolocation API provides a function to get the current location and another one to watch the location of the user. Both functions takes a function as input. The function which will be taken as input receives the current location of the users.

⁄⁄does the browser support the Geolocation API?
if(navigator.geolocation) 
{   
//will call setPosition once navigator.geolocation.getCurrentPosition(setPosition);
//will call setPosition multiple times with the current position var id = navigator.geolocation.watchPosition(scrollMap); } function setPosition(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude;
//your code }

The position object contains a attribute coordinate which stores longitude, latitude and altitude. But it also contains information about how accurate these position information are. The heading attribute, in the coordinate object, contains the direction of travel specified in degrees which is relative to north. Also a speed attribute is provided which contains the speed in meters of the device. The specification of the Coordinates interface looks as follows:

interface Coordinates {
  readonly attribute double latitude;
  readonly attribute double longitude;
  readonly attribute double? altitude;
  readonly attribute double accuracy;
  readonly attribute double? altitudeAccuracy;
  readonly attribute double? heading;
  readonly attribute double? speed;
};

The Geolocation API is a great thing to build web applications which shows location specific information. It is very accurate and it is easy to use with a map provider like Google or Bing. The web in the future will contain more localized information than it already contains today, so keep an eye on this API!

4 thoughts on “Localize the user with the javascript Geolocation API

Comments are closed.