Cached Positions in the Geolocation API

The Geolocation API is surprisingly short and simple. A simple lookup is a doddle:


  1. navigator.geolocation.getCurrentPosition(function(position) {
  2.   alert("You're at " + position.coords.latitude + ","
  3.           + position.coords.longitude);
  4. });

About the most complicated thing is “cached positions”, and even those are quite straightforward. So what’s that all about?

A cached position is what the API returns when you don’t need a live, “this is where the user is right now”, position. Geo-lookups can be time-consuming, so sometimes you might opt for a slightly stale location instead of making the user wait for a lookup. You might also be helping the user to reduce battery life or bandwidth consumption.

In the simplest usage, a real lookup will always occur:


  1. navigator.geolocation.getCurrentPosition(showMap); // no options? no cache for you.

However, you can also say “I’ll happily accept a location from the past minute (60,000 ms) if you know it”


  1. navigator.geolocation.getCurrentPosition
  2.   (showMap, handleError, {maximumAge:60000});

Set maximumAge as Infinity (a valid Javascript literal) to say “just give me a cached value you cached any time, I don’t care how far back”.

Using a second timeout parameter, you can force the position to be cached, i.e. prevent a lookup altogether, even if there’s no cached value, in which case you get an error.


  1. navigator.geolocation.getCurrentPosition
  2.   (showMap, handleError, {maximumAge:60000, timeout:0});

(The spec uses “position” and “location” interchangeably; ideally a spec like this would use a single term, but at least in this case they do mean almost the same thing.)

Leave a Reply