J.P. Cummins

Geolocation in HTML 5


One of the really cool features of HTML 5 is the Geolocation API. Geolocation lets users to share their location with trusted websites. When the user allows the website to gather their location, the browser submits latitude and longitude to the website through a JavaScript callback. The website can then use the information to do fancy location-aware things like finding a nearby theater or mapping houses for sale in your neighborhood.

How does it work?

The Geolocation API consists of a single JavaScript object, navigator.geolocation. If the navigator object doesn't exist, the browser simply doesn't support geolocation.

If the navigator object exists, the next step in detecting location is to call geolocation.getCurrentPosition:

navigator.geolocation.getCurrentPosition(callback)

When called, the browser asks the user for permission to submit their location.

Thankfully, the geolocation API states that browsers “must not send location information to Web sites without the express permission of the user.”

Once permission is granted, the JavaScript callback is invoked with a location object. The object is populated with all sorts of goodies such as latitude, longitude, altitude, heading, and speed.

function callback(location) { 
  var latitude = location.coords.latitude;
  var longitude = location.coords.longitude;
}

Further Reading

I've only scratched the surface of the Geolocation API. If you're interested in learning more, I recommend reading the following sites:

Geolocation in Action

Below is a demo I created for the Geolocation API. It asks for location information, displays a Google map, and inspects the location object returned by the browser.

Note: I don't store or share any location information.