Latest web development tutorials

HTML5 Geolocation


The HTML Geolocation API is used to locate a user's position.

 

What's W3C Geolocation API?

The W3C Geolocation API is an effort by the World Wide Web Consortium (W3C) to standardize an interface to retrieve the geographical location information for a client-side device.

It defines a set of objects, ECMAScript standard compliant, that executing in the client application give the client's device location through the consulting of Location Information Servers, which are transparent for the application programming interface (API).

The most common sources of location information are IP address, Wi-Fi and Bluetooth MAC address, radio-frequency identification (RFID), Wi-Fi connection location, or device Global Positioning System (GPS) and GSM/CDMA cell IDs.

The location is returned with a given accuracy depending on the best location information source available.


Deployment in web browsers

Web pages can use the Geolocation API directly if the web browser implements it. Historically, some browsers could gain support via the Google Gears plugin, but this was discontinued in 2010 and the server-side API it depended on stopped responding in 2012.

The Geolocation API is ideally suited to web applications for mobile devices such as personal digital assistants (PDA) and smartphones. On desktop computers, the W3C Geolocation API works in Firefox since version 3.5, Google Chrome, Opera 10.6, Internet Explorer 9.0, and Safari 5. On mobile devices, it works on Android (firmware 2.0+), iOS, Windows Phone and Maemo.

The W3C Geolocation API is also supported by Opera Mobile 10.1 — available for Android and Symbian devices (S60 generations 3 & 5) since November 24, 2010.

Google Gears provided geolocation support for older and non-compliant browsers, including Internet Explorer 7.0+ as a Gears plugin, and Google Chrome which implemented Gears natively. It also supported geolocation on mobile devices as a plugin for the Android browser (pre version 2.0) and Opera Mobile for Windows Mobile.

However, the Google Gears Geolocation API is incompatible with the W3C Geolocation API and is no longer supported.


Features

The result of W3C Geolocation API will usually give 4 location properties, including latitude and longitude (coordinates), altitude (height), and [accuracy of the position gathered], which all depend on the location sources.

In some queries, altitude may yield or return no value.


Locate the User's Position

The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise privacy, the position is not available unless the user approves it.


Browser Support

The numbers in the table specify the first browser version that fully supports Geolocation.

API          
Geolocation 5.0 9.0 3.5 5.0 16.0

Note: Geolocation is much more accurate for devices with GPS, like iPhone.


Using HTML Geolocation

The getCurrentPosition() method is used to get the user's position.

The example below returns the latitude and longitude of the user's position:

Example

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>
Try it Yourself »

Example explained:

  • Check if Geolocation is supported
  • If supported, run the getCurrentPosition() method. If not, display a message to the user
  • If the getCurrentPosition() method is successful, it returns a coordinates object to the function specified in the parameter (showPosition)
  • The showPosition() function outputs the Latitude and Longitude

The example above is a very basic Geolocation script, with no error handling.


Handling Errors and Rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user's location:

Example

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = "Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = "An unknown error occurred."
            break;
    }
}
Try it Yourself »

Displaying the Result in a Map

To display the result in a map, you need access to a map service, like Google Maps.

In the example below, the returned latitude and longitude is used to show the location in a Google Map (using a static image):

Example

function showPosition(position) {
    var latlon = position.coords.latitude + "," + position.coords.longitude;

    var img_url = "http://maps.googleapis.com/maps/api/staticmap?center=
    "+latlon+"&zoom=14&size=400x300&sensor=false";

    document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
Try it Yourself »

Google Map Script
How to show an interactive Google Map with a marker, zoom and drag options.


Location-specific Information

This page demonstrated how to show a user's position on a map.

Geolocation is also very useful for location-specific information, like:

  • Up-to-date local information
  • Showing Points-of-interest near the user
  • Turn-by-turn navigation (GPS)

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties are returned if available:

Property Returns
coords.latitude The latitude as a decimal number
coords.longitude The longitude as a decimal number
coords.accuracy The accuracy of position
coords.altitude The altitude in meters above the mean sea level
coords.altitudeAccuracy The altitude accuracy of position
coords.heading The heading as degrees clockwise from North
coords.speed The speed in meters per second
timestamp The date/time of the response

Geolocation object - Other interesting Methods

watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).

clearWatch() - Stops the watchPosition() method.

The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):

Example

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude +
    "<br>Longitude: " + position.coords.longitude;
}
</script>
Try it Yourself »