HTML5 Geo Location

Jakob Jenkov
Last update: 2014-06-15

The HTML geo location feature enables your web application to obtain the geographical position of your website visitors. Geo location is not actually part of the HTML5 specification, but since HTML5 has become the de facto label for all the new features in HTML and JavaScript, I have included geo location in this HTML5 tutorial.

Security and Privacy

The user has to accept that your website accesses their location via a browser dialog, so you cannot use it for spying on your visitors without their knowing.

Accessing Geo Location

Geo location is accessed via JavaScript, through the navigator.geolocation object in the browser. The geo location object allows you to access geo location through two primary functions:

  1. getCurrentPosition()
  2. watchPosition()

The getCurrentPosition() function returns the location of the visitor as a one-time snapshot. The watchPosition() function returns the location of the visitor every time the location changes. It does so by calling the given success or error callback functions whenever the position changes.

Both functions take the following parameters:

  • Success callback function
  • Error callback function (optional)
  • Geo location options object (optional)

As you can see, some of the parameters are optional. Here is an example that accesses the users geo location, and passes only the success callback function to getCurrentPosition():

navigator.geolocation.getCurrentPosition(
    function(position) {
        alert("your position is: "
                + position.coords.latitude + ", "
                + position.coords.longitude);
    }
);

To try the example, click this button:

The geo location is obtained asynchronously. That means, that when you call getCurrentPosition() or watchPosition() the functions return immediately. When the browser knows the location of the user, and the user has accepted that the website may access the geo location, the success callback function is called. If an error occurs, the error callback function is called instead.

The Position Object

The position object passed to the success callback function looks like this:

double latitude         // read only attribute
double longitude        // read only attribute
double accuracy         // read only attribute

double altitude         // read only attribute
double altitudeAccuracy // read only attribute
double heading          // read only attribute
double speed            // read only attribute

The latitude and longitude properties contains the geopgrahical coordinates of the position. The accuracy property contains the accuracy of the location in meters. The lower the accuracy is, the more precise the location is.

The altitude, altitudeAccuracy, heading and speed are available only if the device running the browser has a GPS embedded. Otherwise these properties are set to null.

The altitude property contains the altitude of the user. The altitudeAccuracy contains the accuracy in meters of the altitude. The heading property tells the direction the user is moving. The value is in degrees (0-360) relative to true north. The speed property contains the users speed in meters per second, if available.

Speed

The speed property seems only to have a value if you are using the watchPosition() method. The browser apparently needs a few positions in order to calculate a speed.

The Error Callback Function

If obtaining the users geo location fails, the error callback function passed to either getCurrentPosition() or watchPosition() will be called. Failing to obtain the geo location may fail for the following reasons:

  • The user denies the website access to geo location.
  • The device running the browser cannot obtain the geo location, e.g. if the device is in a tunnel, underground etc. where GPS satelite signals cannot be received.
  • The device is too long time about obtaining the position, and the call times out.

The error callback function receives an object with two properties, like this:

short     code    // unsigned read only attribute.
DOMString message // read only attribute.

The value of the code attribute will be one of:

  • 1, meaning PERMISSION_DENIED
  • 2, meaning POSSITION_UNAVAILABLE
  • 3, meaning TIMEOUT

The message attribute contains a textual description of the error. This error may be useful for a developer, but may not make much sense for the website user.

The Geo Location Options Object

The getCurrentPosition() and watchPosition() functions can take a geo location options object as the third parameter. This options object can contain the following properties:

    enableHighAccuracy     // true or false
    timeout                // milliseconds
    maximumAge             // milliseconds

The enableHighAccuracy property can be either true or false. A value of true signals to the browser that if the device running the browser has a GPS, it should be enabled. Keep in mind that the GPS takes a lot of power, so don't require it enabled unless it is necessary with the high accuracy.

The timeout property tells the browser how long time to wait when trying to obtain a position, before timing out and calling the error callback function instead of the success callback function.

The maximumAge attribute tells the browser the maximum age in milliseconds of a cached location, that your application will accept. A value of 0 means that the browser must obtain a new location upon each call to the success callback function.

A Full HTML5 Geo Location Example

Here is a code example that uses both a success callback handler, an error callback handler, and an options object:

navigator.geolocation.getCurrentPosition(
    function(position) {
        alert("your position is: "
                + position.coords.latitude + ", "
                + position.coords.longitude);
    }
    ,
    function(errorObject) {
        alert("Error obtaining position");
    }
    ,
    {
      enableHighAccuracy : true,
      timeout    : 3000,
      maximumAge : 60000
    }
);

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next