This specification defines an API that provides scripted access to geographical location information associated with the hosting device.
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the most recently formally published revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
If you wish to make comments regarding this document, please send them to public-geolocation@w3.org ( subscribe , archives ). All feedback is welcome.
Implementors should be aware that this specification is not stable. Implementors who are not taking part in the discussions are likely to find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation stage should join the aforementioned mailing list and take part in the discussions.
The Geolocation Working Group is responsible for this document. This is just an informal proposal at this time.
[If you keep the <!--comment--> the table of contents will be included here automatically.]
All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.
The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this document are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]
Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.
Conformance requirements phrased as algorithms or specific steps may be implemented in any manner, so long as the end result is equivalent. (In particular, the algorithms defined in this specification are intended to be easy to follow, and not intended to be performant.)
User agents may impose implementation-specific limits on otherwise unconstrained inputs, e.g. to prevent denial of service attacks, to guard against running out of memory, or to work around platform-specific limitations.
Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification, as this specification uses that specification's terminology. [WEBIDL]
This section is non-normative.
The Geolocation API defines a high-level interface to location information associated only with the device hosting the implementation, such as latitude and longitude. The API itself is agnostic of the underlying location information sources. Common sources of location information include 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. No guarantee is given that the API returns the device's actual location.
The API is designed to enable both "one-shot" position requests and repeated position updates, as well as the ability to explicitly query the cached positions. Location information is represented by latitude and longitude coordinates. The Geolocation API in this specification builds upon earlier work in the industry, including [AZALOC] , [GEARSLOC] , and [LOCATIONAWARE] .
The following code extract illustrates how to obtain basic location information:
Example of a "one-shot" position request.
function showMap(position) { // Show a map centered at (position.coords.latitude, position.coords.longitude). } // One-shot position request. navigator.geolocation.getCurrentPosition(showMap);
Example of requesting repeated position updates.
function scrollMap(position) { // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude). } // Request repeated updates. var watchId = navigator.geolocation.watchPosition(scrollMap); function buttonClickHandler() { // Cancel the updates when the user clicks a button. navigator.geolocation.clearWatch(watchId); }
Example of requesting repeated position updates and handling errors.
function scrollMap(position) { // Scrolls the map so that it is centered at (position.coords.latitude, position.coords.longitude). } function handleError(error) { // Update a div element with error.message. } // Request repeated updates. var watchId = navigator.geolocation.watchPosition(scrollMap, handleError); function buttonClickHandler() { // Cancel the updates when the user clicks a button. navigator.geolocation.clearWatch(watchId); }
Example of requesting a potentially cached position.
// Request a position. We accept positions whose age is not // greater than 10 minutes. If the User Agent does not have a // fresh enough cached position object, it will automatically // acquire a new one. navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge:600000}); function successCallback(position) { // By using the 'maximumAge' option above, the position // object is guaranteed to be at most 10 minutes old. } function errorCallback(error) { // Update a div element with error.message. }
Forcing the User Agent to return a fresh cached position.
// Request a position. We only accept cached positions whose age is not // greater than 10 minutes. If the User Agent does not have a fresh // enough cached position object, it will immediately invoke the error // callback. navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge:600000, timeout:0}); function successCallback(position) { // By using the 'maximumAge' option above, the position // object is guaranteed to be at most 10 minutes old. // By using a 'timeout' of 0 milliseconds, if there is // no suitable cached position available, the User Agent // will immediately invoke the error callback with code // TIMEOUT and will not initiate a new position // acquisition process. } function errorCallback(error) { switch(error.code) { case error.TIMEOUT: // Quick fallback when no suitable cached position exists. doFallback(); // Acquire a new position object. navigator.geolocation.getCurrentPosition(successCallback, errorCallback); break; case ... // treat the other error cases. }; } function doFallback() { // No fresh enough cached position available. // Fallback to a default position. }
Forcing the User Agent to return any available cached position.
// Request a position. We only accept cached positions, no matter what // their age is. If the User Agent does not have a cached position at // all, it will immediately invoke the error callback. navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {maximumAge:Infinity, timeout:0}); function successCallback(position) { // By setting the 'maximumAge' to Infinity, the position // object is guaranteed to be a cached one. // By using a 'timeout' of 0 milliseconds, if there is // no cached position available at all, the User Agent // will immediately invoke the error callback with code // TIMEOUT and will not initiate a new position // acquisition process. if (position.timestamp < freshness_threshold && position.coords.accuracy < accuracy_threshold) { // The position is relatively fresh and accurate. } else { // The position is quite old and/or inaccurate. } } function errorCallback(error) { switch(error.code) { case error.TIMEOUT: // Quick fallback when no cached position exists at all. doFallback(); // Acquire a new position object. navigator.geolocation.getCurrentPosition(successCallback, errorCallback); break; case ... // treat the other error cases. }; } function doFallback() { // No cached position available at all. // Fallback to a default position. }
This section is non-normative.
This specification is limited to providing a scripting API for retrieving geographic position information associated with a hosting device. The geographic position information is provided in terms of World Geodetic System coordinates [WGS84] .
The scope of this specification does not include providing a markup language of any kind.
The scope of this specification does not include defining new URI schemes for building URIs that identify geographic locations.
The API defined in this specification can be used to retrieve the geographic location of a hosting device. In almost all cases, this information also discloses the location of the user of the device, thereby potentially compromising the user's privacy. A conforming implementation of this specification must provide a mechanism that protects the user's privacy and this mechanism should ensure that no location information is made available without the user's informed consent.
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 [DOCUMENTORIGIN] . Those permissions that are acquired through the user interface and that are preserved beyond the current browsing session (i.e. beyond the time when the browsing context [BROWSINGCONTEXT] is navigated to another URL) must be revocable and User Agents must respect revoked permissions.
Some User Agents will have prearranged trust relationships that do not require such user interfaces. For example, while a Web browser will present a user interface when a Web site performs a geolocation request, a VOIP telephone may not present any user interface when using location information to perform an E911 function.
Recipients must only request location information when necessary. Recipients must only use the location information for the task for which it was provided to them. Recipients must dispose of location information once that task is completed, unless expressly permitted to retain it by the user. Recipients must also take measures to protect this information against unauthorized access. If location information is stored, users should be allowed to update and delete this information.
The recipient of location information must not retransmit the location information without the user’s consent. Care should be taken when retransmitting and use of encryption is encouraged.
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. This disclosure must include an explanation of any exceptions to the guidelines listed above.
The above recommendations requre that the
user consent to actions that might put the user's privacy at risk,
such as the storage or forwarding of the user's location. This API
provides a basic mechanism for UAs to provide permissions to
recipients, namely through the rules
attribute of a Position
object. Recipients that wish to perform
actions that are not allowed under these Privacy Considerations
(for example, storing location information or sending it other
places) should check these rules to see if such actions are
permitted.
This section is non-normative.
Further to the requirements listed in the previous section, implementors of the Geolocation API are also advised to consider the following aspects that may negatively affect the privacy of their users: in certain cases, users may inadvertently grant permission to the User Agent to disclose their location to Web sites. In other cases, the content hosted at a certain URL changes in such a way that the previously granted location permissions no longer apply as far as the user is concerned. Or the users might simply change their minds.
Predicting or preventing these situations is inherently difficult. Mitigation and in-depth defensive measures are an implementation responsibility and not prescribed by this specification. However, in designing these measures, implementers are advised to enable user awareness of location sharing, and to provide easy access to interfaces that enable revocation of permissions.
The Geolocation
object
can be used by scripts to programmatically determine the location
information associated with the hosting device. The location
information is acquired by applying a user-agent specific
algorithm, creating a Position
object, and populating that object with appropriate data
accordingly.
Objects implementing the Navigator
interface (e.g.
the window.navigator
object) must also implement the
NavigatorGeolocation
interface. [NAVIGATOR] . An instance
of NavigatorGeolocation
would be then obtained by
using binding-specific casting methods on an instance of
Navigator
.
[NoInterfaceObject] interface NavigatorGeolocation { readonly attribute Geolocation geolocation; };
interface Geolocation { void getCurrentPosition(in PositionCallback successCallback, [Optional] in PositionErrorCallback errorCallback, [Optional] in PositionOptions options); int watchPosition(in PositionCallback successCallback, [Optional] in PositionErrorCallback errorCallback, [Optional] in PositionOptions options); void clearWatch(in int watchId); }; interface PositionCallback { void handleEvent(in Position position); }; interface PositionErrorCallback { void handleEvent(in PositionError error); };
The getCurrentPosition()
takes one, two or three arguments. When called, it must immediately
return and then asynchronously acquire a new Position
object. If successful, this method
must invoke its associated successCallback
argument
with a Position
object as an
argument. If the attempt fails, and the method was invoked with a
non-null errorCallback
argument, this method must
invoke the errorCallback
with a PositionError
object as an
argument.
The watchPosition()
takes one, two or three arguments. When called, it must immediately
return and then asynchronously start a watch process defined
as the following set of steps:
Position
object. If successful, invoke the associated
successCallback
with a Position
object as an argument. If the
attempt fails, and the method was invoked with a non-null
errorCallback
argument, this method must invoke the
errorCallback
with a PositionError
object as an
argument.Position
object every time the implementation
determines that the position of the hosting device has
changed.This method returns an integer value that uniquely identifies
the watch process. When the clearWatch()
method is called with
this identifier, the watch process must stop acquiring any new
position fixes and must cease invoking any callbacks.
The getCurrentPosition()
and
watchPosition()
methods
accept PositionOptions
objects as their third argument.
PositionOptions
objects are regular ECMAScript objects that have the following
properties:
[NoInterfaceObject] interface PositionOptions { attribute boolean enableHighAccuracy; attribute long timeout; attribute long maximumAge; };
The enableHighAccuracy
, timeout
and
maximumAge
attributes are all optional: when creating
a PositionOptions object, the developer may specify any of these
attributes.
The enableHighAccuracy
attribute
provides a hint that the application would like to receive the best
possible results. This may result in slower response times or
increased power consumption. The user might also deny this
capability, or the device might not be able to provide more
accurate results than if the flag wasn't specified.
enableHighAccuracy
is trying to solve.The timeout
attribute
denotes the maximum length of time (expressed in milliseconds) that
is allowed to pass from the call to
getCurrentPosition()
or watchPosition()
until the corresponding successCallback
is invoked. If
the implementation is unable to successfully acquire a new
Position
before the given timeout elapses, and no
other errors have occurred in this interval, then the corresponding
errorCallback
must be invoked with a
PositionError
object whose code attribute is set to
TIMEOUT .
Before executing a call to
getCurrentPosition()
or watchPosition()
,
an implementation may first need to acquire the user's permission
to disclose location information to the current application origin.
In such a case, the timeout interval starts immediately after the
user's permission has been successfully acquired.
In case of a getCurrentPosition()
call, the
errorCallback
would be invoked exactly once.
In case of a watchPosition()
, the
errorCallback
could be invoked repeatedly: the first
timeout is relative to the moment watchPosition()
was
called, while subsequent timeouts are relative to the moment when
the implementation determines that the position of the hosting
device has changed and a new Position
object must be
acquired.
The maximumAge
attribute
indicates that the application is willing to accept a cached
position whose age is no greater than the specified time in
milliseconds. If maximumAge
is not specified or set to
0, the implementation must immediately attempt to acquire a new
position object. Setting the maximumAge
to Infinity
will force the implementation to return a cached position
regardless of its age. If an implementation does not have a cached
position available whose age is no greater than the specified
maximumAge
, then it must acquire a new position
object. In case of a watchPosition()
, the
maximumAge
refers to the first position object
returned by the implementation.
The Position
interface is the container for the
geolocation information returned by this API. This version of the
specification allows one attribute of type Coordinates
and a timestamp
. Future versions of the
API may allow additional attributes that provide other information
about this position (e.g. street addresses).
interface Position { readonly attribute Coordinates coords; readonly attribute DOMTimeStamp timestamp; readonly attribute PrivacyRules rules; };
The coords
attribute
contains a set of geographic coordinates together with their
associated accuracy, as well as a set of other optional attributes
such as altitude and speed.
The timestamp
attribute
represents the time when the Position
object was
acquired and is represented as a DOMTimeStamp [DOMTIMESTAMP] .
The rules
attribute contains a set of user preferences
that may give the recipient permission to use the
Position
object in ways that would not otherwise be allowed by
the Privacy Considerations discussed above. For example, the rules
might allow the recipient to store or retransmit the location
object.
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; };
The geographic coordinate reference system used by the attributes in this interface is the World Geodetic System (2d) [WGS84] . No other reference system is supported.
The latitude
and longitude
attributes are geographic
coordinates specified in decimal degrees.
The altitude
attribute
denotes the height of the position, specified in meters above the
[WGS84] ellipsoid. If the implementation
cannot provide altitude information, the value of this attribute
must be null.
The accuracy
attribute
denotes the accuracy level of the latitude and longitude
coordinates. It is specified in meters and must be supported by all
implementations.
The altitudeAccuracy
attribute
is specified in meters. If the implementation cannot provide
altitude information, the value of this attribute must be null.
The accuracy
and altitudeAccuracy
values returned by an implementation should correspond to a 95%
confidence level.
The heading
attribute
denotes the direction of travel of the hosting device and is
specified in degrees counting clockwise relative to the true north.
If the implementation cannot provide heading information, the value
of this attribute must be null.
The speed
attribute denotes
the current ground speed of the hosting device and is specified in
meters per second. If the implementation cannot provide speed
information, the value of this attribute must be null.
interface PrivacyRules { readonly attribute boolean retransmissionAllowed; readonly attribute DOMTimeStamp retentionExpires; };
Privacy rules allow users to grant location recipients permission to use their location information in ways that would not otherwise be permitted by the Privacy Considerations above. The user can permit the site to send location information to other sites (e.g., components in a mash-up) or to store location information for longer periods of time. Future versions of this API may include additional rules elements to allow the user to provide new or different permissions to recipients.
If a site needs specific permissions, it
may request permission through the privacy attributes of the
PositionOptions
object.
The retransmissionAllowed
attribute specifies whether the user permits the
recipient to send the attached location information to other
entities. If this option is true
,then the site
may send the attached location to other sites, but should still
only do so as necessary to complete the task for which the location
was provided. If this option is null
,false
,or otherwise
not present, then the recipient must handle this location object as
described in the Privacy Considerations above, i.e., it must not
retransmit the location without obtaining user permission (through
some other means).
The retentionExpires
attribute specifies the latest time that the recipient
may keep the attached location information. If the attribute is not
null, then the recipient must delete the information before the
indicated time. If this attribute is null
or not present,
then the recipient must handle this location object as described in
the Privacy Considerations above. That is, it must delete the
location object after it has been used for its intended
purpose.
interface PositionError { const unsigned short UNKNOWN_ERROR = 0; 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; };
The code
attribute must return
the appropriate code from the following list:
UNKNOWN_ERROR
(numeric value 0)PERMISSION_DENIED
(numeric value 1)POSITION_UNAVAILABLE
(numeric value 2)TIMEOUT
(numeric
value 3)The message
attribute must
return an error message describing the details of the error
encountered. This attribute is primarily intended for debugging and
developers should not use it directly in their application user
interface.
Issue note: This section will get moved to a separate document
Someone visiting a foreign city could access a Web application that allows users to search or browse through a database of tourist attractions. Using the Geolocation API, the Web application has access to the user's approximate position and it is therefore able to rank the search results by proximity to the user's location.
A group of friends is hiking through the Scottish highlands. Some of them write short notes and take pictures at various points throughout the journey and store them using a Web application that can work offline on their hand-held devices. Whenever they add new content, the application automatically tags it with location data from the Geolocation API (which, in turn, uses the on-board GPS device). Every time they reach a town or a village, and they are again within network coverage, the application automatically uploads their notes and pictures to a popular blogging Web site, which uses the geolocation data to construct links that point to a mapping service. Users who follow the group's trip can click on these links to see a satellite view of the area where the notes were written and the pictures were taken. Another example is a life blog where a user creates content (e.g. images, video, audio) that records her every day experiences. This content can be automatically annotated with information such as time, geographic position or even the user's emotional state at the time of the recording.
A user finds herself in an unfamiliar city area. She wants to check her position so she uses her hand-held device to navigate to a Web-based mapping application that can pinpoint her exact location on the city map using the Geolocation API. She then asks the Web application to provide driving directions from her current position to her desired destination.
A mapping application can help the user navigate along a route by providing detailed turn-by-turn directions. The application does this by registering with the Geolocation API to receive repeated location updates of the user's position. These updates are delivered as soon as the implementing User Agent determines that the position of the user has changed, which allows the application to anticipate any changes of direction that the user might need to do.
A tour-guide Web application can use the Geolocation API to monitor the user's position and trigger visual or audio notifications when interesting places are in the vicinity. An online task management system can trigger reminders when the user is in the proximity of landmarks that are associated with certain tasks.
A widget-like Web application that shows the weather or news that are relevant to the user's current area can use the Geolocation API to register for location updates. If the user's position changes, the widget can adapt the content accordingly.
A social network application allows its users to automatically tag their status updates with location information. It does this by monitoring the user's position with the Geolocation API. Each user can control the granularity of the location information (e.g. city or neighbourhood level) that is shared with the other users. Any user can also track his network of friends and get real-time updates about their current location.
Alec Berntson, Alissa Cooper, Steve Block, Greg Bolsinga, Aaron Boodman, Dave Burke, Chris Butler, Max Froumentin, Shyam Habarakada, Marcin Hanclik, Ian Hickson, Brad Lassey, Angel Machin, Daniel Park, Stuart Parmenter, Olli Pettay, Chris Prince, Arun Ranganathan, Aza Raskin, Carl Reed, Thomas Roessler, Dirk Segers, Allan Thomson, Martin Thomson, Doug Turner, Erik Wilde, Mohamed Zergaoui