in Development

How to use the Geolocation API

Geolocation is a new standard that allow us to identify where a user is located by the use of scripts within the browser.

Geolocation-example

This is particularly useful when we want to offer in our web app local information to the users. Some examples of it could be a web app that tells you where is the nearest bus station, a restaurant or just to know where you are when you get lost in the city. Something that by the way, happens to me a lot.

The first thing you need to know is that the Geolocation API just defines a high-level interface to access the geolocation information, but it is completely agnostic on the system used to obtain that geolocation information.

 

 

There are several ways to get the information like:

  • GPS
  • GSM/CDMA cell IDs
  • IP address

As you can already imagine the accuracy of the results will depend a lot on how the geolocation information is retrieved.

Now that we have a little bit of background, let’s see more in detail what the Geolocation API offer us. The API defines a new interface that is called, not surprisingly, Geolocation. This interface defines three methods:

//Used to retrieve the current geolocation, just one time.
void getCurrentPosition(
     //Callback to receive geolocation info
     in PositionCallback successCallback,
     //Callback to receive errors produced during the call
     in optional PositionErrorCallback errorCallback,
     //Options about the geolocation information to retrieve
     in optional PositionOptions options);

//Used to track the geolocation of the user.
long watchPosition(
     //Callback to receive geolocation info
     in PositionCallback successCallback,
     //Callback to receive errors produced during the call
     in optional PositionErrorCallback errorCallback,
     //Options about the geolocation information to retrieve
     in optional PositionOptions options);

//Used to stop tracking the geolocation of the user.
void clearWatch(
     //id of the watch retrieved with watchPosition
     in long watchId);

At this point you will have already noticed that the method getCurrentPosition does not return any value, this is because the API is asynchronous, so in order to obtain the results we need to implement a callback function (PositionCallback) that will be called once the method has the results.

The other two parameters are optional, they let us to define another callback function to receive any error produced while calling the method and the different options to configure the geolocation information that will be retrieved.

Before we proceed to implement a real example let’s examine the rest of classes used in the API:

// used to receive successful notifications about position requests
interface PositionCallback {
    void handleEvent(in Position position);
}

// used to receive error notifications about position requests
interface PositionErrorCallback {
    void handleEvent(in PositionError error);
} 

// used to specify the options about the geolocation information to retrieve
interface PositionOptions {
    // by default false. Indicates you want to obtain the information with
    // the best accuracy available, even if that consumes more battery or
    // means slower response time.
    attribute boolean enableHighAccuracy;
    
    // expressed in milliseconds
    long timeout;

    // expressed in milliseconds. Indicates you accept a cached value
    // no greater than the specified time. If 0, acquires a new position
    long maximumAge
} 

// used to obtain geolocation position information
interface Position {
    readonly Coordinates coords;
    readonly DOMTimeStamp timestamp;
} 

// used to obtain errors while requesting geolocation information
interface PositionError {
    const unsigned short PERMISSION_DENIED = 1;
    const unsigned short POSITION_UNAVAILABLE = 2;
    const unsigned short TIMEOUT = 3;
    readonly attribute unsigned short code;
    readonly attribute DOMString message;
}

// used to obtain the geolocation position details
interface Coordinates {
    //specified in decimal degrees
    readonly attribute double latitude;
    //specified in decimal degrees
    readonly attribute double longitude;
    // specified in meters
    readonly attribute double? altitude;
    // specified in meters and corresponding to 95% confidence level
    readonly attribute double accuracy;
    // specified in meters and corresponding to 95% confidence level
    readonly attribute double? altitudeAccuracy;
    // specified in degrees, denotes the direction of travel counting
    // clockwise relative to the true north (0º to 360º)
    readonly attribute double? heading;
    // specified in meters per second
    readonly attribute double? speed;
}

Now that we have all info we can start creating a real example, to test them you will need any of the modern browsers that supports this feature like Internet Explorer 9.

In the above example we have seen:

  • how to request the position of the visitor who is accessing our web page
  • how to load a Bing map using the Bing Maps API and set a pushpin in the map indicating our current location
  • how to handle the errors in the case the geolocation information could not be retrieved.
  • Related Content by Tag