Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
The
Geolocation.getCurrentPosition()
method is used to get
the current position of the device.
Syntax
getCurrentPosition(success)
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)
Parameters
success
-
A callback function that takes a
GeolocationPosition
object as its
sole input parameter. error
Optional-
An optional callback function that takes a
GeolocationPositionError
object as its sole input parameter. options
Optional-
An optional object including the following parameters:
maximumAge
-
A positive
long
value indicating the maximum age in milliseconds of a possible cached position that is acceptable to return. If set to0
, it means that the device cannot use a cached position and must attempt to retrieve the real current position. If set toInfinity
the device must return a cached position regardless of its age. Default: 0. timeout
-
A positive
long
value representing the maximum length of time (in milliseconds) the device is allowed to take in order to return a position. The default value isInfinity
, meaning thatgetCurrentPosition()
won’t return until the position is available. enableHighAccuracy
-
A boolean value that indicates the application would like to receive the best possible results. If
true
and if the device is able to provide a more accurate position, it will do so. Note that this can result in slower response times or increased power consumption (with a GPS chip on a mobile device for example). On the other hand, iffalse
, the device can take the liberty to save resources by responding more quickly and/or using less power. Default:false
.
Return value
Examples
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
Specifications
Specification |
---|
Geolocation API # getcurrentposition-method |
Browser compatibility
BCD tables only load in the browser
See also
Abstract
The Geolocation API provides access to geographical location
information associated with the hosting device.
Status of This Document
This section describes the status of this
document at the time of its publication. A list of current W3C
publications and the latest revision of this technical report can be found
in the W3C technical reports index at
https://www.w3.org/TR/.
The Devices and Sensors Working Group is updating this specification in
the hope of making it a «living standard». As such, we’ve dropped the
«Editions» and aim to continue publishing updated W3C Recommendations
of this specification as we add new features or fix bugs.
This document was published by the Devices and Sensors Working Group as
a Recommendation using the
Recommendation track.
W3C recommends the wide deployment of this specification as a standard for
the Web.
A W3C Recommendation is a specification that, after extensive
consensus-building, is endorsed by
W3C and its Members, and
has commitments from Working Group members to
royalty-free licensing
for implementations.
Future updates to this Recommendation may incorporate
new features.
This document was produced by a group
operating under the
W3C Patent
Policy.
W3C maintains a
public list of any patent disclosures
made in connection with the deliverables of
the group; that page also includes
instructions for disclosing a patent. An individual who has actual
knowledge of a patent which the individual believes contains
Essential Claim(s)
must disclose the information in accordance with
section 6 of the W3C Patent Policy.
This document is governed by the
2 November 2021 W3C Process Document.
This section is non-normative.
The Geolocation API 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 grants permission, the
Geolocation API:
- Provides location data as latitude, longitude, altitude, speed, and
heading, as well as the accuracy of the acquired location data, and the
approximate time for when the position was acquired via the
GeolocationPosition
interface. - Supports «one-shot» position updates via the
getCurrentPosition
()
method and the ability to receive
updates for when the position of the hosting device significantly
changes via thewatchPosition
()
method. - Using the
PositionOptions
‘smaximumAge
,
allows an application to request a cached position whose age is no
greater than a specified value (only the last position is cached). - Provides a way for the application to receive updates about errors,
as aGeolocationPositionError
, that have occurred while acquiring a position. - And through
enableHighAccuracy
, supports
requesting «high accuracy» position data, though the request can be
ignored by the user agent.
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]. 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.
This section is non-normative.
Since First Public Working Draft in 2021, the Geolocation
API has received the following normative changes:
- fix «Queue a task» / «in parallel» usage (#118)
- Suggest permission lifetime (#108)
- Handle OS-level permission change (#109)
- Switch DOMTimeStamp to EpochTimeStamp (#104)
- Return 0 when watchPosition() errors (#100)
- Callback with error if doc is not fully active (#97)
- Gracefully handle documents that are not fully active (#90)
- Add «geolocation task queue» (#87)
Since publication of the Second Edition in 2016, this specification
has received the following changes:
- Request a position only proceeds when a document is visible,
or the document becomes visible. - Clarified how caching works as part of acquiring a position:
only last position is cached, and can be evicted at any time. - Now relies on the Permissions specification to handle
permission grants, and user interface requirements. - The
errorCallback
is now nullable. - The API can be controlled by Permissions Policy, which
restricts how/where the API is exposed to web pages. - The
callbacks
are no longer treated as «EventHandler» objects
(i.e., objects that have a.handleEvent()
method), but are now
exclusively treated as IDL callback functions. - The API is now only exposed in Secure Contexts (i.e., only
available in HTTPS). - The interfaces no longer use [WebIDL]’s legacy
[NoInterfaceObject]
, soGeolocation
and other interface of this
spec are now in the global scope. Also, the interfaces were renamed
fromNavigatorGeolocation*
to justGeolocation*
.
See the commit
history for a complete list of changes.
This section is non-normative.
The API is designed to enable both «one-shot» position requests and
repeated position updates. The following examples illustrate common use
cases.
This section is non-normative.
Request the user’s current location. If the user allows it, you will
get back a position object.
This section is non-normative.
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.
This section is non-normative.
Stop watching for position changes by calling the
clearWatch
()
method.
This section is non-normative.
When an error occur, the second argument of the
watchPosition
()
or
getCurrentPosition
()
method gets called with a
GeolocationPositionError
error, which can help you figure out
what might have gone wrong.
This section is non-normative.
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
timeout
member to
limit the amount of time you are willing to wait to acquire a position.
This section is non-normative.
The default allowlist of 'self'
allows Geolocation 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
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.
This section is non-normative.
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.
This section is non-normative.
The Geolocation API 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
getCurrentPosition
()
and
watchPosition
()
methods rely.
An end-user will generally give express permission through a user
interface, which usually present a range of permission
lifetimes that the end-user can choose from. The
choice of 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 lifetimes dictate
how long a user agent 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 lifetime
varies across user-agents, this specification urges user agents to
limit the lifetime to a single browsing session by default (see
3.4
Checking permission to use the API for normative requirements).
This section is non-normative.
Note: Developers’ responsibility with this sensitive data
This section applies to «recipients», which generally means
developers utilizing the Geolocation API. 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.
This section is non-normative.
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.
The Geolocation API is a default powerful feature
identified by the name "geolocation"
.
When checking permission
to use the API, a user agent MAY suggest time-based permission
lifetimes, such as «24 hours», «1 week», or choose to
remember the permission grant indefinitely. However,
it is RECOMMENDED that a user agent prioritize restricting the
permission lifetime to a single session: This can
be, for example, until the 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 API at
the time of publication. However, readers are advised to read the
3.
Privacy considerations.
partial interface Navigator {
[SameObject] readonly attribute Geolocation
geolocation
;
};
[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 referenceto the last acquired position and serves as a cache. A user agent MAY evict [[cachedPosition]] by resetting it tonull at any time for any reason. |
[[watchIDs]] |
Initialized as an empty list of unsigned long items. |
The getCurrentPosition
(successCallback,
errorCallback, options)
method steps are:
- If the current settings object’s relevant global object’s
associatedDocument
is not fully active:- Call back with error errorCallback and
POSITION_UNAVAILABLE
. - Terminate this algorithm.
- Call back with error errorCallback and
- In parallel, request a position passing
successCallback, errorCallback, and options.
The watchPosition
(successCallback,
errorCallback, options)
method steps are:
- If the current settings object’s relevant global object’s
associatedDocument
is not fully active:- Call back with error passing errorCallback and
POSITION_UNAVAILABLE
. - Return 0.
- Call back with error passing errorCallback and
- Let watchId be an implementation-defined
unsigned long
that is greater than zero. - Append watchId to this’s
[[watchIDs]]
. - In parallel, request a position passing
successCallback, errorCallback, options, and watchId. - Return watchId.
When clearWatch()
is invoked, the user agent MUST:
- Remove watchId from this’s
[[watchIDs]]
.
To request a position, pass a PositionCallback
successCallback, a PositionErrorCallback?
errorCallback, PositionOptions
options, and an optional watchId:
- Let watchIDs be this’s
[[watchIDs]]
. - Let document be the current settings object’s
relevant global object’s associatedDocument
. - If document is not allowed to use the
«geolocation» feature:- If watchId was passed, remove watchId from
watchIDs. - Call back with error passing errorCallback and
PERMISSION_DENIED
. - Terminate this algorithm.
- If watchId was passed, remove watchId from
- If document‘s visibility state is
«hidden», wait for the following page visibility change steps to
run:- Assert: document‘s visibility state is
«visible». - Continue to the next steps below.
- Assert: document‘s visibility state is
- Let descriptor be a new
PermissionDescriptor
whose
name
is"geolocation"
. - Set permission to request permission to use descriptor.
-
If permission is «denied», then:
- If watchId was passed, remove watchId from
watchIDs. - Call back with error passing errorCallback and
PERMISSION_DENIED
. - Terminate this algorithm.
- If watchId was passed, remove watchId from
- Wait to acquire a position passing successCallback,
errorCallback, options, and watchId. - If watchId was not passed, terminate this algorithm.
- While watchIDs contains watchId:
-
Wait for a significant change of
geographic position. What constitutes a significant
change of geographic position is left to the implementation.
User agents MAY impose a rate limit on how frequently position
changes are reported. - If document is not fully active or
visibility state is not «visible», go back to the
previous step and again wait for a
significant change of geographic position.Note: Position updates are exclusively for fully-active visible documents
- Wait to acquire a position passing successCallback,
errorCallback, options, and watchId.
-
Wait for a significant change of
To acquire a position,
passing PositionCallback
successCallback, a
PositionErrorCallback?
errorCallback,
PositionOptions
options, and an optional
watchId.
- If watchId was passed and this’s
[[watchIDs]]
does not contain watchId,
terminate this algorithm. - Let acquisitionTime be a new
EpochTimeStamp
that represents now. - Let timeoutTime be the sum of acquisitionTime and
options.timeout
. - Let cachedPosition be this’s
[[cachedPosition]]
. - Create an implementation-specific timeout task that elapses at
timeoutTime, during which it tries to acquire the device’s position
by running the following steps:- Let permission be get the current permission state of
"geolocation"
. - If permission is «denied»:
- Stop timeout.
- Do the user or system denied
permission failure case step.
- If permission is «granted»:
- Let position be null.
- If cachedPosition is not null, and
options.maximumAge
is greater than 0:- Let cacheTime be acquisitionTime minus the
value of the options.maximumAge
member. - If cachedPosition‘s
timestamp
‘s value is greater than
cacheTime, and
cachedPosition.[[isHighAccuracy]]
equals options.enableHighAccuracy
,
set position to cachedPosition.
- Let cacheTime be acquisitionTime minus the
- Otherwise, if position is not cachedPosition, try to
acquire position data from the underlying system, optionally
taking into consideration the value of
options.enableHighAccuracy
during
acquisition. - If the timeout elapses during acquisition, or acquiring
the device’s position results in failure:- Stop the timeout.
- Go to dealing with
failures. - Terminate this algorithm.
- If acquiring the position data from the system succeeds:
- Set position be a new
GeolocationPosition
passing acquisitionTime and
options.enableHighAccuracy
. - Set this’s
[[cachedPosition]]
to
position.
- Set position be a new
- Stop the timeout.
- Queue a task on the geolocation task source with
a step that invokes successCallback with position.
- Dealing with failures:
-
- If acquiring a position fails, do one of the following
based on the condition that matches the failure:- User or system denied permission:
-
Call back with error passing errorCallback and
PERMISSION_DENIED
.Note: Browser permission VS OS permission
- Timeout elapsed:
-
Call back with error with errorCallback and
TIMEOUT
. - Data acquisition error or any other reason:
-
Call back with error passing errorCallback and
POSITION_UNAVAILABLE
.
- If acquiring a position fails, do one of the following
- Let permission be get the current permission state of
When instructed to call back with error, given an
PositionErrorCallback?
callback and an
unsigned short
code:
- If callback is null, return.
- Let error be a newly created
GeolocationPositionError
instance whose
code
attribute is initialized to code. - Queue a task on the geolocation task source with a step
that invokes callback with error.
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).
Note: A word of warning about enableHighAccuracy
The timeout
member denotes the maximum length of time,
expressed in milliseconds, before acquiring a position expires.
Note: When is the timeout calculated?
The time spent waiting for the document to become visible and for
obtaining permission to use the API is not
included in the period covered by the timeout
member. The timeout
member only applies when
acquiring a position begins.
Note: Immediate cancellation
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
;
};
The coords
attribute contains geographic coordinates.
The timestamp
attribute represents the time when the
geographic position of the device was acquired.
Instances of GeolocationPositionError
are created with the
internal slots in the following table:
Internal slot | Description |
---|---|
[[isHighAccuracy]] |
A boolean that records the value of theenableHighAccuracy member when thisGeolocationPosition is created.
|
The following task source is defined by this specifications.
- The geolocation task source
-
Used by this specification to queue up non-blocking
PositionCallback
andPositionErrorCallback
when performing
position requests.
[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
;
};
The latitude
and longitude
attributes are
geographic coordinates specified in decimal degrees.
The accuracy
attribute denotes the accuracy level of the
latitude and longitude coordinates in meters (e.g., 65
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.
A new GeolocationPosition
is constructed with
EpochTimeStamp
timestamp and boolean
isHighAccuracy by performing the following steps:
- Let coords be a newly created
GeolocationCoordinates
instance:- Initialize coord‘s
latitude
attribute to a geographic coordinate in decimal degrees. - Initialize coord‘s
longitude
attribute to a geographic coordinate in decimal degrees. - Initialize coord‘s
accuracy
attribute to a non-negative real number. The value SHOULD
correspond to a 95% confidence level with respect to the
longitude and latitude values. - Initialize coord‘s
altitude
attribute in meters above the [WGS84] ellipsoid, ornull
if
the implementation cannot provide altitude information. - Initialize coord‘s
altitudeAccuracy
attribute as
non-negative real number, or tonull
if the implementation
cannot provide altitude information. If the altitude accuracy
information is provided, it SHOULD correspond to a 95% confidence
level. - Initialize coord‘s
speed
attribute to a non-negative real number, or asnull
if the
implementation cannot provide speed information. - Initialize coord‘s
heading
attribute in degrees, ornull
if the implementation cannot
provide heading information. If the hosting device is stationary
(i.e., the value of thespeed
attribute is 0), then initialize the
heading
toNaN
.
- Initialize coord‘s
- Return a newly created
GeolocationPosition
instance with its
coords
attribute initialized to coords and
timestamp
attribute initialized to
timestamp, and its[[isHighAccuracy]]
internal slot set to isHighAccuracy.
[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
;
};
-
PERMISSION_DENIED
(numeric value 1) -
Request a position failed because the user denied permission to
use the API. -
POSITION_UNAVAILABLE
(numeric value 2) - Acquire a position failed.
-
TIMEOUT
(numeric value 3) -
The length of time specified by the
timeout
member has elapsed before the user agent could successfully
acquire a position.
The code
attribute returns the value it was initialized to (see 10.1
Constants for possible
values).
The message
attribute is a developer-friendly textual
description of the code
attribute.
Note: Don’t show .message to users!
The Geolocation API defines a policy-controlled feature identified by the token string "geolocation"
. Its
default allowlist is 'self'
.
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words MAY, MUST, RECOMMENDED, and SHOULD in this document
are to be interpreted as described in
BCP 14
[RFC2119] [RFC8174]
when, and only when, they appear in all capitals, as shown here.
partial interface Navigator {
[SameObject] readonly attribute Geolocation
geolocation
;
};
[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
);
dictionary PositionOptions
{
boolean enableHighAccuracy
= false;
[Clamp] unsigned long timeout
= 0xFFFFFFFF;
[Clamp] unsigned long maximumAge
= 0;
};
[Exposed=Window, SecureContext]
interface GeolocationPosition
{
readonly attribute GeolocationCoordinates
coords
;
readonly attribute EpochTimeStamp timestamp
;
};
[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
;
};
[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
;
};
-
A new GeolocationPosition
§9.5 -
accuracy
attribute forGeolocationCoordinates
§9.1 -
acquire a position
§6.6 -
altitude
attribute forGeolocationCoordinates
§9.2 -
altitudeAccuracy
attribute forGeolocationCoordinates
§9.2 -
[[cachedPosition]]
internal slot forGeolocation
§6.1 -
call back with error
§6.7 -
checking permission
§3.4 -
clearWatch()
method forGeolocation
§6.4 -
code
attribute forGeolocationPositionError
§10.2 -
coords
attribute forGeolocationPosition
§8.1 -
enableHighAccuracy
member forPositionOptions
§7.1 -
geolocation
attribute forNavigator
§5. -
Geolocation
interface
§6. -
geolocation task source
§8.4 -
"geolocation"
§3.4 -
GeolocationCoordinates
interface
§9. -
GeolocationPosition
interface
§8. -
GeolocationPositionError
interface
§10. -
getCurrentPosition
method forGeolocation
§6.2 -
heading
attribute forGeolocationCoordinates
§9.3 -
[[isHighAccuracy]]
internal slot forGeolocationPosition
§8.3 -
latitude
attribute forGeolocationCoordinates
§9.1 -
longitude
attribute forGeolocationCoordinates
§9.1 -
maximumAge
member forPositionOptions
§7.3 -
message
attribute forGeolocationPositionError
§10.3 -
PERMISSION_DENIED
§10.1 -
POSITION_UNAVAILABLE
§10.1 -
PositionCallback
§6. -
PositionErrorCallback
§6. -
PositionOptions
dictionary
§7. -
request a position
§6.5 -
speed
attribute forGeolocationCoordinates
§9.4 -
timeout
member forPositionOptions
§7.2 -
TIMEOUT
§10.1 -
timestamp
attribute forGeolocationPosition
§8.2 -
[[watchIDs]]
internal slot forGeolocation
§6.1 -
watchPosition
method forGeolocation
§6.3
-
[PERMISSIONS] defines the following:
- Permissions
-
[PERMISSIONS-POLICY] defines the following:
- Permissions Policy
-
[WEBIDL] defines the following:
- unsigned long type
This section is non-normative.
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.
- [RFC2119]
- Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc2119
- [RFC8174]
- Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL: https://www.rfc-editor.org/rfc/rfc8174
- [webidl]
- Web IDL Standard. Edgar Chen; Timothy Gu. WHATWG. Living Standard. URL: https://webidl.spec.whatwg.org/
- [WGS84]
- National Imagery and Mapping Agency Technical Report 8350.2, Third Edition. National Imagery and Mapping Agency. 3 January 2000.
- [Permissions]
- Permissions. Marcos Caceres; Mike Taylor. W3C. 30 July 2022. W3C Working Draft. URL: https://www.w3.org/TR/permissions/
- [Permissions-Policy]
- Permissions Policy. Ian Clelland. W3C. 16 July 2020. W3C Working Draft. URL: https://www.w3.org/TR/permissions-policy-1/
Improve Article
Save Article
Improve Article
Save Article
In this article, we will know HTML Geolocation getCurrentPosition() Method, various parameters, & their implementation through the examples. HTML5 provides us the Geolocation API which helps us to identify the geographic location of the user. The Geolocation API gives the latitude and longitude of the user’s current location which are further sent to the backend using JavaScript and then the current location of the user is shown on the website.
The getCurrentPosition() method is used for getting the current location of the user.
Syntax:
navigator.geolocation.getCurrentPosition(success, error, options);
Parameter values:
- success: It is a function that is called after the data is successfully gathered by the getCurrentPosition() method from the API.
- error: It is also a callback function that returns the warnings and the error messages of the location.
- options: It helps us to set a timeout, enableHighAccuracy, and maximumAge.
Please refer to the HTML Geolocation article for the various properties, methods & their implementation in detail.
Example: The below example illustrate the Geolocation getCurrentPosition() Method by checking the user’s geolocation.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Get Current Position</
title
>
</
head
>
<
body
>
<
h2
>Welcome To GFG</
h2
>
<
div
>
<
button
onclick
=
"geolocator()"
>click me</
button
>
<
p
id
=
"paraGraph"
></
p
>
</
div
>
<
script
>
var paraGraph = document.getElementById("paraGraph");
var user_loc = navigator.geolocation;
function geolocator() {
if(user_loc) {
user_loc.getCurrentPosition(success);
} else {
"Your browser doesn't support geolocation API";
}
}
function success(data) {
var lat = data.coords.latitude;
var long = data.coords.longitude;
paraGraph.innerHTML = "Latitude: "
+ lat
+ "<
br
>Longitude: "
+ long;
}
</
script
>
</
body
>
</
html
>
Output:
Getting the user’s current geolocation.
Example 2: To Display timestamp and Accuracy.
HTML
<!DOCTYPE html>
<
html
>
<
head
>
<
title
>Get Current Location</
title
>
</
head
>
<
body
>
<
h2
>Welcome To GFG</
h2
>
<
div
>
<
button
onclick
=
"geolocator()"
>click me</
button
>
<
p
id
=
"paraGraph"
></
p
>
</
div
>
<
script
>
var paraGraph = document.getElementById("paraGraph");
var user_loc = navigator.geolocation;
function geolocator() {
if(user_loc) {
user_loc.getCurrentPosition(success);
} else {
"Your browser doesn't support geolocation API";
}
}
function success(data) {
var accu = data.coords.accuracy;
var tmstmp = data.timestamp;
paraGraph.innerHTML = "Accuracy: "
+ accu
+ "<
br
>Time Stamp: "
+ tmstmp;
}
</
script
>
</
body
>
</
html
>
Output:
Getting the timestamp and Accuracy of a user
Supported Browsers:
- Google Chrome 5.0
- Microsoft Edge 12.0
- Internet Explorer 9.0
- Firefox 3.5
- Opera 10.6
- Safari 5.0
На этом уроке мы познакомимся с объектом navigator
, который предназначен для получения различной информации о браузере.
Объект navigator
предназначен для предоставления подробной информации о браузере, который пользователь использует для доступа к сайту или веб-приложению. Кроме данных о браузере, в нём ещё содержится сведения о операционной системе, сетевом соединении и др.
Объект navigator
– это свойство window
:
const navigatorObj = window.navigator; // или без указания window // const navigatorObj = navigator;
Объект navigator
имеет свойства и методы. Очень часто они используется для того чтобы узнать, какие функции поддерживаются браузером, а какие нет.
Свойства объекта navigator
:
appCodeName
– кодовое имя браузера;appName
– имя браузера;appVersion
— версия браузера;cookieEnabled
— позволяет определить включены ли cookie в браузере;geolocation
— используется для определения местоположения пользователя;language
— язык браузера;online
— имеет значениеtrue
илиfalse
в зависимости от того находиться ли браузер в сети или нет;platform
— название платформы, для которой скомпилирован браузер;product
— имя движка браузера;userAgent
— возвращает заголовокuser agent
, который браузер посылает на сервер.
Методы объекта navigator
:
javaEnabled
– позволяет узнать, включён ли в браузере Java;sendBeacon
— предназначен для отправки небольшого количества информации на веб-сервер без ожидания ответа.
Пример
Например, выведем все свойства и методы объекта Navigator на веб-страницу:
<div id="navig" class="alert alert-waring"> </div> <script> var navig = ""; for (var property in navigator) { navig += "<strong>"+property+"</strong> :" + navigator[property]; navig +="<br />"; } document.getElementById("navig").innerHTML = navig; </script>
Обнаружение браузера с помощью userAgent
userAgent
— это строка, содержащая информацию о браузере, которую он посылает в составе заголовка запроса на сервер.
Пример содержания строки userAgent
в браузере Google Chrome:
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36
Она содержит сведения об операционной системе, браузере, версиях, платформах и т.д.
Эти данные можно использовать, например, для обнаружения браузера. Для этого можно написать следующую функцию:
const detectBrowser = () = { let result = 'Other'; if (navigator.userAgent.indexOf('YaBrowser') !== -1 ) { result = 'Yandex Browser'; } else if (navigator.userAgent.indexOf('Firefox') !== -1 ) { result = 'Mozilla Firefox'; } else if (navigator.userAgent.indexOf('MSIE') !== -1 ) { result = 'Internet Exploder'; } else if (navigator.userAgent.indexOf('Edge') !== -1 ) { result = 'Microsoft Edge'; } else if (navigator.userAgent.indexOf('Safari') !== -1 ) { result = 'Safari'; } else if (navigator.userAgent.indexOf('Opera') !== -1 ) { result = 'Opera'; } else if (navigator.userAgent.indexOf('Chrome') !== -1 ) { result = 'Google Chrome'; } return result; }
Зачем это нужно? Например для того, чтобы запускать некоторые скрипты или функции только в определенном браузере.
Но при использовании navigator.userAgent
следует иметь в виду, что эта информация не является 100% достоверной, поскольку она может быть изменена пользователем.
Вообще не существует 100% надежных способов идентификации браузера. Поэтому лучше проверять доступность необходимой функции или свойства, и если этой поддержки нет, то написать обходной код для реализации этого функционала или вообще его не предоставлять для этих браузеров.
Определение мобильного устройства посредством userAgent
Самый простой способ обнаружить мобильные устройства — это найти слово mobile
в пользовательском агенте (userAgent
):
const isMobile = navigator.userAgent.toLowerCase().match(/mobile/i); if (isMobile) { // для мобильных устройств } else { // для не мобильных устройств }
Более подробный вариант идентификации мобильного браузера:
const isMobile = navigator.userAgent.toLowerCase().match(/mobile/i); const isTablet = navigator.userAgent.toLowerCase().match(/tablet/i); const isAndroid = navigator.userAgent.toLowerCase().match(/android/i); const isiPhone = navigator.userAgent.toLowerCase().match(/iphone/i); const isiPad = navigator.userAgent.toLowerCase().match(/ipad/i);
Объект geolocation
Объект geolocation
предназначен для определения местоположения устройства. Доступ к этому объекту осуществляется через свойство «navigator.geolocation
»:
const geo = navigator.geolocation; // или так // const geo = window.navigator.geolocation;
Узнать поддерживает ли браузер геолокацию, можно посредством проверки существования свойства geolocation
в объекте navigator
:
if (!navigator.geolocation) { console.error('Ваш браузер не поддерживает геолокацию!'); }
При этом, когда сайт или веб-приложение пытается получить доступ к местонахождению пользователя, браузер из соображений конфиденциальности предоставит его только в том случае если это разрешит пользователь.
Получение текущего местоположения пользователя
Получение текущего местоположения пользователя осуществляется через метод getCurrentPosition
.
// аргумент success - обязательный navigator.geolocation.getCurrentPosition(success[, error[, options]);
Этот метод посылает асинхронный запрос. В случае успеха мы можем получить местоположение устройства, в противном случае – нет.
Метод getCurrentPosition
принимает 3 аргумента:
success
— функцию обратного вызова, которая будет вызвана при успешном получении геоданных (т.е. когда пользователь разрешил доступ сайту или веб-приложению к Geolocation API и данный API определил местоположение пользователя);error
— функцию обратного вызова, которая вызывается при ошибке (т.е. когда пользователь не разрешил доступ к Geolocation API, или данный API не смог определить местонахождение пользователя, или истекло время ожиданияtimeout
);options
— объект, содержащий настройки.
В options
можно установить:
maximumAge
— следует ли информацию о местонахождении пользователя кэшировать (в миллисекундах) или пытаться всегда получать реальное значение (значение 0 — по умолчанию);timeout
— максимальное время в миллисекундах в течении которого нужно ждать ответ (данные о местоположении); если ответ за указанное время не пришёл, то вызывать функцию обратного вызоваerror
(по умолчанию имеет значениеinfinity
, т.е. ждать бесконечно);enableHighAccuracy
— при значенииtrue
будет пытаться получить наилучшие результаты, т.е. более точное местоположение (для этого может понадобиться задействовать GPS), что в свою очередь может привести к более длительному времени отклика или увеличению энергопотребления; по умолчанию —false
.
В функцию success
передаётся в качестве первого аргумента объект GeolocationPosition
. Он содержит информацию о местоположении устройства (coords
) и времени, когда оно было получено (timestamp
).
Объект coords
содержит следующие свойства:
latitude
— широта (в градусах);longitude
— долгота (в градусах);altitude
— высота над уровнем моря (в метрах);speed
— скорость устройства в метрах в секунду; это значение может бытьnull
.
Пример получения местоположения устройства:
// при успешном получении сведений о местонахождении function success(position) { // position - объект GeolocationPosition, содержащий информацию о местонахождении const latitude = position.coords.latitude; const longitude = position.coords.longitude; const altitude = position.coords.altitude; const speed = position.coords.speed; // выведем значения в консоль console.log(`Широта: ${latitude}°`); console.log(`Долгота: ${longitude}°`); console.log(`Высота над уровнем моря: ${altitude}м`); console.log(`Скорость: ${speed}м/c`); } function error() { console.log('Произошла ошибка при определении местоположения!'); } if (!navigator.geolocation) { // получаем текущее местоположение пользователя navigator.geolocation.getCurrentPosition(success, error); }
Методы watchPosition и clearWatch
Метод watchPocation
используется когда нужно получать данные о местоположении каждый раз, когда оно меняется. Метод возвращает целое число, являющееся идентификатором задачи.
navigator.geolocation.watchPosition(success[, error[, options]])
Метод clearWatch
предназначен для удаления задачи по её идентификатору, которую вы создали посредством watchPosition
.
// создаём задачу и сохраняем её идентификатор в watchId let watchId = navigator.geolocation.watchPosition(success, error, options); // удаляем задачу по её идентификатору clearWatch(watchId);