Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Localize a user with the JavaScript Geolocation API

0.00/5 (No votes)
21 May 2010CPOL1 min read 17.6K  
The web in the future will contain more localized information than it already contains today. The Javascript Geolocation API contains the tools you need to localize a user of your web site.

Javascript provides a function to get the location of the current user of your web page. Currently it is only implemented 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 shows 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 position object, which contains the location information of the user.

JavaScript
//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 an 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:

JavaScript
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)