My favorites | English | Sign in

Sign up for Google I/O 2010 today!

Geolocation API

The Geolocation API enables a web application to obtain a user's geographical position.

Contents

  1. Overview
  2. Example
  3. Classes
    1. Geolocation class
    2. Position class
    3. PositionOptions class
    4. PositionError class
    5. Coords class
    6. Address class

Overview

The Geolocation API enables a web application to:

  • Obtain the user's current position, using the getCurrentPosition method
  • Watch the user's position as it changes over time, using the watchPosition method
  • Quickly and cheaply obtain the user's last known position, using the lastPosition property

The Geolocation API provides the best estimate of the user's position using a number of sources (called location providers). These providers may be onboard (GPS for example) or server-based (a network location provider). The getCurrentPosition and watchPosition methods support an optional parameter of type PositionOptions which lets you specify which location providers to use.

To find out how to implement your own network location provider for use with the Geolocation API, see the description of the Geolocation API network protocol that Gears uses to communicate with network location providers.

Permission

A site's permission to use location information is separate from the permission required by other Gears APIs. Permission is granted by the user in the same way as for other Gears APIs, through a dialog. If you would like to customize the default dialog, you can explicitly call the getPermission method.

Example

<script type="text/javascript" src="gears_init.js"></script>
<script type="text/javascript">
var geo = google.gears.factory.create('beta.geolocation');

function updatePosition(position) {
  alert('Current lat/lon is: ' + position.latitude + ',' + position.longitude);
}

function handleError(positionError) {
  alert('Attempt to get location failed: ' + positionError.message);
}

geo.getCurrentPosition(updatePosition, handleError);
</script>

Classes

Geolocation class 
  readonly attribute Position lastPosition
  readonly attribute boolean hasPermission
  void getCurrentPosition(successCallback, [errorCallback], [options])
  int  watchPosition(successCallback, [errorCallback], [options])
  void clearWatch(int watchId)
  boolean getPermission([siteName], [imageUrl], [extraMessage])
Position class
  readonly attribute Date timestamp
  readonly attribute Coords coords
  readonly attribute Address gearsAddress
  readonly attribute double latitude
  readonly attribute double longitude
  readonly attribute double accuracy
  readonly attribute double altitude
  readonly attribute double altitudeAccuracy
PositionOptions class
  readwrite attribute bool enableHighAccuracy
  readwrite attribute int maximumAge
  readwrite attribute int timeout
  readwrite attribute bool gearsRequestAddress
  readwrite attribute string gearsAddressLanguage
  readwrite attribute string[] gearsLocationProviderUrls
PositionError class
  readonly attribute int UNKNOWN_ERROR
  readonly attribute int PERMISSION_DENIED
  readonly attribute int POSITION_UNAVAILABLE
  readonly attribute int TIMEOUT
  readonly attribute int code
  readonly attribute string message
Coords class
  readonly attribute double latitude
  readonly attribute double longitude
  readonly attribute double accuracy
  readonly attribute double altitude
  readonly attribute double altitudeAccuracy
Address class
  readonly attribute string streetNumber
  readonly attribute string street
  readonly attribute string premises
  readonly attribute string city
  readonly attribute string county
  readonly attribute string region
  readonly attribute string country
  readonly attribute string countryCode
  readonly attribute string postalCode

Geolocation class

Methods

void getCurrentPosition(successCallback, [errorCallback], [options])
Return value: This method has no return value.
Parameters: successCallback(Position position)
errorCallback(PositionError error) - optional, pass null if you do not want to make use of the callback.
options - optional, specifies the options to use for this request, see PositionOptions.
Description: Provides a previously cached position if available or attempts to obtain a new position.

If PositionOptions.maximumAge is zero, the cached position is not used and a new position fix is always sought. The method will throw an exception if no location providers are used.

If PositionOptions.maximumAge is non-zero, Gears will call the success callback if the cached position is more recent than PositionOptions.maximumAge. If not, Gears will attempt to obtain a new position fix. The error callabck is called exactly once as soon as a position fix is obtained, or the error callnback is called on failure. If the cached position is not sufficiently recent and no location providers are used, the error callback is called.

Whenever Gears attempts to obtain a new position fix, this is subject to PositionOptions.timeout. The error callback is called on timeout.

The signature of the success callback is:
function successCallback(Position position)

The signature of the error callback is:
function errorCallback(PositionError error)
int watchPosition(function successCallback, [function errorCallback], [PositionOptions options])
Return value: A unique watch identifier.
Parameters: successCallback(Position position)
errorCallback(PositionError error) - optional, pass null if you do not want to make use of the callback.
options - optional, specifies the options to use for this request, see PositionOptions.
Description: Provides a previously cached position if available and repeatedly obtains a new position.

If PositionOptions.maximumAge is zero, the cached position is not used and a new position fix is always sought. The method will throw an exception if no location providers are used.

If PositionOptions.maximumAge is non-zero, Gears will call the success callback if the cached position is more recent than PositionOptions.maximumAge. If any case, Gears will then attempt to obtain a new position fix. The success callback function is called as soon as a good position is available and whenever the position changes significantly, subject to a maximum callback frequency. The error callback is called if a fatal error occurs which will prevent a position fix from ever being obtained by this watch. If the cached position is not sufficiently recent and no location providers are used, the error callback is called.

Whenever Gears attempts to obtain a new position fix, this is subject to PositionOptions.timeout. The error callback is called on timeout when obtaining the first position fix, or if Gears detects that the device has moved, but is unable to obtain a new position fix within the time specifed by PositionOptions.timeout.

The signature of the success callback is:
function successCallback(Position position)

The signature of the error callback is:
function errorCallback(PositionError error)
void clearWatch(int watchId)
Return value: This method has no return value.
Parameter: watchId - the identifier of the watch to stop.
Description: Stop watching the current position.
boolean getPermission([siteName], [imageUrl], [extraMessage])
Return value: Indicates whether the site has permission to access the user's location through Gears.
Parameters: siteName - optional, friendly name of the site requesting permission.
imageUrl - optional, URL of a .png file to display in the dialog.
extraMessage - optional, site-specific text to display to users in the security dialog.
Description: Lets a site manually trigger the Gears location security dialog, optionally with UI customizations.

It is always safe to call this function; it will return immediately if the site already has permission to access the user's location through Gears. All arguments are optional. The dialog will only show those that are specified.

Attributes

Attribute Type Description
lastPosition readonly Position The last known position, or null if there is no last known position. This does not actively trigger obtaining a new position fix, so it is quick and does not consume power or computational resources.
hasPermission readonly boolean Returns true if the site already has permission to access the user's location through Gears.

Position class

Attributes

Attribute Type Description
timestamp readonly Date The time when the location was established.
coords readonly Coords The coordinates of the position, expressed as a latitude, longitude and altitude. See Coords.
gearsAddress readonly Address A reverse-geocoded address, if requested and available. See Address.
latitude readonly double Deprecated. Applications should use Position.coords.latitude.
longitude readonly double Deprecated. Applications should use Position.coords.longitude.
accuracy readonly double Deprecated. Applications should use Position.coords.accuracy.
altitude readonly double Deprecated. Applications should use Position.coords.altitude.
altitudeAccuracy readonly double Deprecated. Applications should use Position.coords.altitudeAccuracy.

PositionOptions class

Attributes

Attribute Type Description
enableHighAccuracy readwrite bool Optional, requests the most accurate possible results. This may result in slower response times or increased battery consumption. Also, there is no guarantee that the device will be able to provide more accurate results than if this flag is not specified. The default value is false.
maximumAge readwrite int Optional, specifies the maximum permissible age of a cached position provided by the getCurrentPosition and watchPosition methods. When either of these methods is called, if Gears has a cached permission and it is more recent than the specified maximum age, the success callback will be called immediatley with this cached position. If not, Gears will attempt to obtain a new position fix. If a value of Infinity is specified, no time limit is applied. The default value is zero, meaning that a cached position is never used and Gears wil always attempt to get a new position fix.
timeout readwrite int Optional, specifies the maximum time period for which Gears should attempt to obtain a position fix. If a position fix can not be obtained within this period, the error callback is invoked with code 3. The value is limited to a non-negative signed 32 bit signed integer. If this value is not set, no time limit is applied.
gearsRequestAddress readwrite bool Optional, requests reverse geocoded address information as part of the position data. Reverse geocoding is not performed if this flag is not specified or if it is set to false.
gearsAddressLanguage readwrite string Optional, specifies the language in which the address (if requested) should be returned. Specify the language in accordance with RFC 3066, en-GB for British English for example.

If this is not specified, the address is provided in the default language of the location provider used to perform the reverse geocoding.
gearsLocationProviderUrls readwrite string[] Optional, specifies one or more URLs to contact to convert geolocation signals into positions. If unset, defaults to a single Google-implemented service. The array can also be cleared, or set to null, so that no location providers are used.

PositionError class

Attributes

Attribute Type Description
UNKNOWN_ERROR readonly int W3C Geolocation API error code constant. Not used by Gears.
PERMISSION_DENIED readonly int W3C Geolocation API error code constant. Not used by Gears
POSITION_UNAVAILABLE readonly int W3C Geolocation API error code constant. No position fix could be obtained.
TIMEOUT readonly int W3C Geolocation API error code constant. The specified maximum time elapsed before a position could be obtained.
code readonly int A code identifying the reason for the error. Possible values are listed below. Note that Gears does not use all of the W3C Geolocation API error codes.
  • PositionError.POSITION_UNAVAILABLE
  • PositionError.TIMEOUT
message readonly string A human readable message, suitable for logs.

Coords class

Attributes

Attribute Type Description
latitude readonly double Latitude in degrees using the World Geodetic System 1984 (WGS84) datum.
longitude readonly double Longitude in degrees (WGS84 datum).
accuracy readonly double The horizontal accuracy of the position in meters, or null if not available.
altitude readonly double Height in meters (WGS84 datum), or null if not available.
altitudeAccuracy readonly double The vertical accuracy of the position in meters, or null if not available.

Address class

Attributes

Attribute Type Description
streetNumber readonly string The building's street number.
street readonly string Street name.
premises readonly string Premises, e.g. building name.
city readonly string City name.
county readonly string County name.
region readonly string Region, e.g. a state in the US.
country readonly string Country.
countryCode readonly string Country code (ISO 3166-1).
postalCode readonly string Postal code. This is the zip code in the US and postcode in the UK.