Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼

Web Development

HTML5's Geolocation

Ed Spencer is a developer for ExtJS.

One of the more immediately useful components of HTML5 is Geolocation. Various imprecise forms of geolocation have been in use on the web for some time, usually in the form of a crude best-guess based on your IP address. Today we have a plethora of new location-aware devices using a variety of location sensing techniques. The HTML5 Geolocation API provides a way to find a device's location without caring how that information is discovered.

The first thing to say about HTML5 Geolocation is that the spec is a working draft and may be subject to change. Support is already in Firefox 3.5+, Safari 5+, Chrome 5+ and Opera 10+. Thankfully, detecting support for it is easy:

if (navigator.geolocation) {
  // do your magic
} else {
  // geolocation is not available... have you considered a forward-thinking browser?

With that caveat out of the way, let's take a look at how we can use it. Geolocation has two main modes of operation -- "one-shot" mode and continuous update mode. Both modes are asynchronous and accept a callback -- here's how we might use one-shot mode to fetch nearby tweets from Twitter:

// our callback function, let's fetch some nearby tweets:
function fetchTweets(position) {
  alert("Fetch tweets from " + position.coords.latitude + ", " + position.coords.longitude);

  // use JSONP to fetch local tweets from twitter

// get the location

The implementation of getting the tweets from Twitter's API is left to the reader but given the coords object it is a relatively simple operation.

A More Complete Example

We have a couple of additional options -- we can provide an error callback if the device's location could not be found for some reason, and an options object giving the geolocation some constraints:

function locationNotFound() {
  alert("Oh noes! We couldn't find you");

var options = {
  timeout: 10000,
  maximumAge: 20000,
  enableHighAccuracy: true

navigator.geolocation.getCurrentPosition(fetchTweets, locationNotFound, options);

The options object API is straightforward: maximumAge tells the browser that if the last location was found less than 20 seconds ago, we will reuse it; otherwise find the location again. The timeout option tells the browser that it should only wait 10 seconds for a location fix before calling the error callback. Finally, enableHighAccuracy is a hint to the browser that we'd like the most accurate location it can give us. The effect of this will vary between devices but usually involves a trade-off, where increased accuracy is paid for with slower response time.

Our success callback is always called with a single object that contains two properties: coords and timestamp. The timestamp is the time that the location was discovered, and coords is the object we used in our fetchTweets function above. As well as latitude and longitude (in degrees), devices may provide altitude (in meters above the reference ellipsoid), the accuracy (in meters) of the latitude and longitude, altitudeAccuracy (again in meters), heading (in degrees relative to true north) and speed (in meters per second).

The error callback gets a much simpler object consisting of a code number and a message string. The code tells the application whether the request failed due to lack of user permission, because the geolocation hardware couldn't find its position or because the operation timed out.

Continuous Updates

The second way to interact with HTML5 Geolocation is through the watchPosition API. Its signature is identical to getCurrentPosition, as are the objects passed to the success and error callbacks that you provide. The only difference is that your success callback will be called every time the device detects that its location has changed. When you no longer need to receive these updates just use the clearWatch function:

//start continuous watching
var watchId = navigator.geolocation.watchPosition(fetchTweets, locationNotFound, options);

//stop watching for updates

HTML5 Geolocation is a young but promising part of HTML5 with a large number of potential applications. It's currently in last call status in the W3C, but seems reasonably settled.

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.