Geolocation provides access to geographical location information associated with the hosting device.
Since this specification become a W3C Recommendation on 01 September 2022, the following substantive additions and/or corrections have been proposed:
A more detailed list of changes can be found in section [[[#changelog]]]. Reviewers of the document can identify candidate additions and/or corrections by their distinctive styling in the document.
Geolocation defines a high-level interface to location information associated only with the device hosting the implementation. 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. The API itself is agnostic of the underlying location information sources, and no guarantee is given that the API returns the device's actual location.
If an end user [=check permission|grants permission=], Geolocation:
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]]. It does not include providing a markup language of any kind, nor does not include defining a new URL scheme for building URLs that identify geographic locations.
The API is designed to enable both "one-shot" position requests and repeated position updates. The following examples illustrate common use cases.
Request the user's current location. If the user allows it, you will get back a position object.
Request the ability to watch user's current location. If the user allows it, you will get back continuous updates of the user's position.
Stop watching for position changes by calling the {{Geolocation/clearWatch()}} method.
When an error occur, the second argument of the {{Geolocation/watchPosition()}} or {{Geolocation/getCurrentPosition()}} method gets called with a {{GeolocationPositionError}} error, which can help you figure out what might have gone wrong.
By default, the API always attempts to return a cached position so long as it has a previously acquired position. In this example, we accept a position whose age is no greater than 10 minutes. If the user agent does not have a fresh enough cached position object, it automatically acquires a new position.
If you require location information in a time sensitive manner, you can use the {{PositionOptions}} {{PositionOptions/timeout}} member to limit the amount of time you are willing to wait to [=acquire a position=].
The [=policy-controlled feature/default allowlist=] of `'self'` allows API usage in same-origin nested frames but prevents third-party content from using the API.
Third-party usage can be selectively enabled by adding the [^iframe/allow^]`="geolocation"` attribute to an [^iframe^] element:
Alternatively, the API can be disabled in a first-party context by specifying an HTTP response header:
See [[[permissions-policy]]] for more details about the `Permissions-Policy` HTTP header.
The API defined in this specification is 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.
Geolocation is a [=powerful feature=] that requires [=express permission=] from an end-user before any location data is shared with a web application. This requirement is normatively enforced by the [=check permission=] steps on which the {{Geolocation/getCurrentPosition()}} and {{Geolocation/watchPosition()}} methods rely.
An end-user will generally give [=express permission=] through a user interface, which usually present a range of permission [=permission/lifetimes=] that the end-user can choose from. The choice of [=permission/lifetimes=] vary across user agents, but they are typically time-based (e.g., "a day"), or until browser is closed, or the user might even be given the choice for the permission to be granted indefinitely. The permission [=permission/lifetimes=] dictate how long a user agent [=permission/grants=] a permission before that permission is automatically reverted back to its default [=permission state=], prompting the end-user to make a new choice upon subsequent use.
Although the granularity of the permission [=permission/lifetime=] varies across user-agents, this specification urges user agents to limit the lifetime to a single browsing session by default (see [[[#check-permission]]] for normative requirements).
This section applies to "recipients", which generally means developers utilizing Geolocation. Although it's impossible for the user agent, or this specification, to enforce these requirements, developers need to read this section carefully and do their best to adhere to the suggestions below. Developers need to be aware that there might be privacy laws in their jurisdictions that can govern the usage and access to users' location data.
Recipients ought to only request position information when necessary, and only use the location information for the task for which it was provided to them. Recipients ought to dispose of location information once that task is completed, unless expressly permitted to retain it by the user. Recipients need to also take measures to protect this information against unauthorized access. If location information is stored, users need to be allowed to update and delete this information.
The recipients of location information need to refrain from retransmitting the location information without the user’s express permission. Care needs to be taken when retransmitting and the use of encryption is encouraged.
Recipients ought to 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 can access, update and delete the data, and any other choices that users have with respect to the data. This disclosure needs to include an explanation of any exceptions to the guidelines listed above.
Implementers are advised to consider the following aspects that can negatively affect the privacy of their users: in certain cases, users can inadvertently grant permission to the user agent to disclose their location to websites. 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 access to user interfaces that enable revocation of permissions.
Geolocation is a [=default powerful feature=] identified
by the [=powerful feature/name=] "geolocation".
When checking permission to use the API, a user agent MAY suggest time-based [=permission=] [=permission/lifetimes=], such as "24 hours", "1 week", or choose to remember the permission [=permission/grant=] indefinitely. However, it is RECOMMENDED that a user agent prioritize restricting the [=permission=] [=permission/lifetime=] to a single session: This can be, for example, until the [=environment settings object/realm=] is destroyed, the end-user [=navigates=] away from the [=origin=], or the relevant browser tab is closed.
There are no security considerations associated with Geolocation at the time of publication. However, readers are advised to read the [[[#privacy]]].
[Exposed=Window]
interface Geolocation {
undefined getCurrentPosition (
PositionCallback successCallback,
optional PositionErrorCallback? errorCallback = null,
optional PositionOptions options = {}
);
long watchPosition (
PositionCallback successCallback,
optional PositionErrorCallback? errorCallback = null,
optional PositionOptions options = {}
);
undefined clearWatch (long watchId);
};
callback PositionCallback = undefined (
GeolocationPosition position
);
callback PositionErrorCallback = undefined (
GeolocationPositionError positionError
);
Instances of {{Geolocation}} are created with the internal slots in the following table:
| Internal slot | Description |
|---|---|
| [[\cachedPosition]] | A {{GeolocationPosition}}, initialized to null. It's a reference to the last acquired position and serves as a cache. A user agent MAY evict {{Geolocation/[[cachedPosition]]}} by resetting it to null at any time for any reason. |
| [[\watchIDs]] | Initialized as an empty [=list=] of {{unsigned long}} [=list/item|items=]. |
The getCurrentPosition(|successCallback:PositionCallback|, |errorCallback:PositionErrorCallback?|, |options:PositionOptions|) method steps are:
The watchPosition(|successCallback:PositionCallback|, |errorCallback:PositionErrorCallback?|, |options:PositionOptions|) method steps are:
When clearWatch() is invoked, the user agent MUST:
To request a position, pass a {{Geolocation}} |geolocation:Geolocation|, a {{PositionCallback}} |successCallback:PositionCallback|, a {{PositionErrorCallback?}} |errorCallback:PositionErrorCallback?|, a {{PositionOptions}} |options:PositionOptions|, and an optional |watchId:unsigned long|:
To acquire a position, passing {{PositionCallback}} |successCallback:PositionCallback|, a {{PositionErrorCallback?}} |errorCallback:PositionErrorCallback?|, {{PositionOptions}} |options:PositionOptions|, and an optional |watchId:unsigned long|.
[=Call back with error=] passing |errorCallback| and {{GeolocationPositionError/PERMISSION_DENIED}}.
When instructed to call back with error, given an {{PositionErrorCallback?}} |callback:PositionErrorCallback?| and an {{unsigned short}} |code:unsigned short|:
dictionary PositionOptions {
boolean enableHighAccuracy = false;
[Clamp] unsigned long timeout = 0xFFFFFFFF;
[Clamp] unsigned long maximumAge = 0;
};
The enableHighAccuracy member provides a hint that the application would like to receive the most accurate location data. The intended purpose of this member is to allow applications to inform the implementation that they do not require high accuracy geolocation fixes and, therefore, the implementation MAY avoid using geolocation providers that consume a significant amount of power (e.g., GPS).
The timeout member denotes the maximum length of time, expressed in milliseconds, before [=acquiring a position=] expires.
The time spent waiting for the document to become visible and for [=check permission|obtaining permission to use the API=] is not included in the period covered by the {{PositionOptions/timeout}} member. The {{PositionOptions/timeout}} member only applies when [=acquiring a position=] begins.
The maximumAge member indicates that the web application is willing to accept a cached position whose age is no greater than the specified time in milliseconds.
[Exposed=Window, SecureContext]
interface GeolocationPosition {
readonly attribute GeolocationCoordinates coords;
readonly attribute EpochTimeStamp timestamp;
[Default] object toJSON();
};
The coords attribute contains geographic coordinates.
The timestamp attribute represents the time when the geographic position of the device was acquired.
The toJSON() method returns a JSON representation of the {{GeolocationPosition}} object.
Instances of {{GeolocationPositionError}} are created with the internal slots in the following table:
| Internal slot | Description |
|---|---|
| [[\isHighAccuracy]] | A {{boolean}} that records the value of the {{PositionOptions/enableHighAccuracy}} member when this {{GeolocationPosition}} is [=a new GeolocationPosition|created=]. |
The following [=task source=] is defined by this specifications.
[Exposed=Window, SecureContext]
interface GeolocationCoordinates {
readonly attribute double accuracy;
readonly attribute double latitude;
readonly attribute double longitude;
readonly attribute double? altitude;
readonly attribute double? altitudeAccuracy;
readonly attribute double? heading;
readonly attribute double? speed;
[Default] object toJSON();
};
The latitude and
longitude attributes are geographic coordinates
specified in decimal degrees. The
latitude and longitude attributes denote the
position, specified as a real number of degrees, in the [[WGS84]]
coordinate system. The accuracy
attribute denotes the position accuracy radius in meters.
The altitude attribute denotes the height of the position, specified in meters above the [[WGS84]] ellipsoid.
The altitudeAccuracy attribute represents the altitude accuracy in meters (e.g., `10` meters).
The heading attribute denotes the direction of travel of the hosting device and is specified in degrees, where 0° ≤ heading < 360°, counting clockwise relative to the true north.
The speed attribute denotes the magnitude of the horizontal component of the hosting device's current velocity in meters per second.
The toJSON() method returns a JSON representation of the {{GeolocationCoordinates}} object.
A new `GeolocationPosition` is constructed with [=map=] |positionData|, {{EpochTimeStamp}} |timestamp:EpochTimeStamp| and boolean |isHighAccuracy| by performing the following steps:
A new `GeolocationPosition` is constructed with {{EpochTimeStamp}} |timestamp:EpochTimeStamp| and boolean |isHighAccuracy| by performing the following steps:
[Exposed=Window]
interface GeolocationPositionError {
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 returns the value it was [=call back with error|initialized to=] (see [[[#constants]]] for possible values).
The message attribute is a developer-friendly textual description of the {{GeolocationPositionError/code}} attribute.
This specification defines a [=policy-controlled feature=] identified by the token string "geolocation". Its [=policy-controlled feature/default allowlist=] is [=default allowlist/'self'=].
For the purposes of user-agent automation and application testing, this document defines geolocation emulations.
Each [=top-level traversable=] has an associated emulated position data, which is data representing {{GeolocationCoordinates}}, {{GeolocationPositionError}} or null, initially null.
To set emulated position data, given [=navigable=] |navigable| and an |emulatedPositionData|:
To get emulated position data, given {{Geolocation}} |geolocation|:
This specification builds upon earlier work in the industry, including research by Aza Raskin, Google Gears Geolocation API, and LocationAware.org.
Thanks also to Alec Berntson, Alissa Cooper, Steve Block, Greg Bolsinga, Lars Erik Bolstad, Aaron Boodman, Dave Burke, Chris Butler, Max Froumentin, Shyam Habarakada, Marcin Hanclik, Ian Hickson, Brad Lassey, Angel Machin, Cameron McCormack, Daniel Park, Stuart Parmenter, Olli Pettay, Chris Prince, Arun Ranganathan, Carl Reed, Thomas Roessler, Dirk Segers, Allan Thomson, Martin Thomson, Doug Turner, Erik Wilde, Matt Womer, and Mohamed Zergaoui.
Since First Public Working Draft in 2021, Geolocation has received the following normative changes:
Since publication of the Second Edition in 2016, this specification received the following substantive changes:
See the commit history for a complete list of changes.