Tutorial: Introduction to Geolocation



Geolocation is one of the features that is often labelled as a HTML5 feature.

Actually, Geolocation is not part of the HTML5 specification, it has its own specification (Geolocation API Specification) and has been created by the W3C rather than the WHATWG but it is worth to discuss about it since it is going to be part of the features that will help developers creating great web applications.


Using geolocation, you can allow your users to:
  • Share their location with others
  • Be "aware" of what is around them depending on their interests
  • Be guided to a direction they want
  • Etc...


Social networking services have a lot of interest on geolocation. Facebook, for instance, recently released places that allow mobile users to share their location, tag friends at some places using geolocation.

Geolocation sounds exciting but there are some privacy concerns, the main one being: "Do I have the ability to accept or refuse which website is getting my location?"

The specification clearly states the following:

User agents must not send location information to Web sites without the express permission of the user. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users, as described below. The user interface must include the URI of the document origin.


Once a user allows the user agent to share the user location with the server, there are still some privacy concerns regarding how long the location data is stored? Is it shared with other sites/partners? Can the location data be updated or deleted by the end user?

The specification recommends the following:

Recipients must clearly and conspicuously disclose the fact that they are collecting location data, the purpose for the collection, how long the data is retained, how the data is secured, how the data is shared if it is shared, how users may access, update and delete the data, and any other choices that users have with respect to the data.


According to the specification, user location can be obtained using
Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs, as well as user input


Now, let us talk about the API. Geolocation API resides in the Geolocation object which is an attribute of the Navigator object. This object provides three methods but two only are used to get user location:
  • getCurrentPosition: gets the user current location once only.
  • watchPosition: regularly keeps polling the user location. Used to watch if the user location has changed. This method returns an long.


Using the id returned by the third Geolocation's method, watchPosition, you can stop watching the position of a user by using the void clearWatch(in long watchId) which is the third method of the Geolocation object.

Both getCurrentPosition and watchPosition take the following arguments:
  • A success callback that takes a Position object as argument. Called if the user allows the browser to share his/her location and there is no error while getting the location information. This callback argument is mandatory.
  • An error callback that takes a PositionError object as argument. Called in case of error while getting the user location. this is an optional argument.
  • A PositionOptions object, also optional, that defines the geolocation options.


For instance, this is how you would call the getCurrentPosition method:
Code:

if (navigator.geolocation) { //Checks if your browser support geolocation
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
error('Sorry, your browser does not support geolocation');
}


Let us now talk about the success callback that is passed as the first argument of the getCurrentPosition and watchPosition methods has only one argument: the Position object.

This Position object has two properties:
  • A Coordinates object (coords) that contains information on user location (accuracy, latitude, longitude, etc).
  • A DOMTimeStamp object (timestamp) that is the time when user location was obtained.


The details of the Coordinates object are the following:
Code:

interface Coordinates {
readonly attribute double latitude;
readonly attribute double longitude;
readonly attribute double? altitude;
readonly attribute double accuracy;
readonly attribute double? altitudeAccuracy;
readonly attribute double? heading;
readonly attribute double? speed;
};

  • latitude and longitude are the geographic coordinates expressed in decimal format
  • altitude represents the altitude in meters
  • accuracy represents the accuracy in meters of the latitude and longitude
  • altitudeAccuracy represents the accuracy in meters of the altitude
  • heading represents degrees clockwise from the true north (with 0å¡ <= heading < 360å¡)
  • speed represents the speed in meters per second


It is important to know that latitude, longitude and accuracy are the attributes that you can be sure to find in any browsers supporting geolocation. Other attributes will just return null if the information cannot be provided.

heading and speed will be calculated based on previous user locations when using watchPosition

Now let us see how to get user location inside the success callback:
Code:

function successCallback(pos) {
alert("Latitude: " + pos.coords.latitude + " , Longitude: " + pos.coords.longitude);
}

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
error('Sorry, your browser does not support geolocation');
}


When calling the getCurrentPosition or the watchPosition method, you can optionally specify an error callback that takes a PositionError object as an argument.

Below are the specifics of the PositionError object:
Code:

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;
};

  • PERMISSION_DENIED: Value returned in the code attribute when the user does not allow the application to get user location.
  • POSITION_UNAVAILABLE: Value returned in the code attribute when the user location cannot be retrieved.
  • TIMEOUT: Value returned in the code attribute when it takes too long to retrieve the user location.
  • code: Attribute containing the error code we have just discussed above.
  • message: Intended for developers. Contains a detailed error message for debugging purpose.


Below is shown how you could create your error callback:
Code:

function errorCallback (err) {
switch(err.code) {
case 1:
alert("Sorry, but this application does not have the permission to use geolocation");
break;
case 2:
alert("Sorry, but a problem happened while getting your location");
break;
case 3:
alert("Sorry, this is taking too long...");
break;
default:
alert("unknown");
}
}

// Success Callback not shown here
// ...
// ...

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
} else {
error('Sorry, your browser does not support geolocation');
}


Finally the last parameter of the getCurrentPosition and the watchPosition method, also optional, is the PositionOptions object.

The PositionOptions object allows the developers to specify options when getting user location.

Code:

interface PositionOptions {
attribute boolean enableHighAccuracy;
attribute long timeout;
attribute long maximumAge;
};

  • enableHighAccuracy: Boolean that specifies if we want to use a higher accuracy mode when getting user location.
  • timeout: Maximum time in milliseconds allowed to get user location. If the user location cannot be retrieved in that time frame, the callback error method would be executed with the TIMEOUT error code.
  • maximumAge: It is possible to use the previous user location in the cache if the time between the last call to get user location and the current call to get user location is below the maximumAge attribute (in milliseconds).


The current browsers supporting geolocation along with their version are Firefox 3.5+, Opera 10.6+, Google Chrome 5+ and Safari 5+
Published December 20, 2010