Geolocation API

On this page 7

The Geolocation API is a browser web API that lets a web page request the geographic position of the user’s device, returned as latitude and longitude with an accuracy radius in meters. It is standardized by the W3C, exposed through the navigator.geolocation object, and available only in secure contexts after the user explicitly grants permission.

Among Web APIs, it is a typical example of a permission-gated capability: the page never sees how the position was obtained, whether from satellite positioning, nearby Wi-Fi networks, cell towers or the IP address. The browser and operating system choose the source, and the page receives only the result and its estimated precision.

How the Geolocation API works

The Geolocation API is asynchronous and callback-based. A page asks for a position, the browser checks or requests permission, the platform’s location service computes an estimate, and the result arrives later in a success callback or an error callback.

MethodPurposeReturns
getCurrentPosition()One-time position requestNothing; result goes to callbacks
watchPosition()Continuous updates when position changesA numeric watch ID
clearWatch()Stops a running watchNothing
Methods of the Geolocation API

A successful result is a GeolocationPosition object containing a coords property and a timestamp. The coords object always includes latitude, longitude and accuracy; it may also include altitude, altitudeAccuracy, heading and speed, which are null when the device cannot measure them. Coordinates use the WGS 84 reference system, the same datum used by satellite navigation.

The accuracy value is a radius in meters around the reported point. A value of 20 means the true position lies within roughly 20 meters, with high confidence; a value of 3,000 means the page knows only the approximate district or town.

Options, accuracy and location sources

Three options control the trade-off between precision, speed and battery use. They are passed as an object to getCurrentPosition() or watchPosition().

OptionDefaultEffect
enableHighAccuracyfalseRequests the most precise source, often satellite positioning
timeoutInfiniteMaximum milliseconds to wait before a timeout error
maximumAge0Accepts a cached position up to this age in milliseconds
Position options and their effect

Typical accuracy depends on which source the platform can use. Desktop browsers usually rely on network information, while phones can combine several sources. The ranges below are indicative and vary with environment, hardware and signal conditions.

SourceTypical accuracyTime to first fixNotes
Satellite positioningAbout 3 to 20 m outdoorsSeconds to over a minutePoor indoors, high battery use
Wi-Fi positioningAbout 15 to 100 mUsually under a few secondsWorks well in cities and buildings
Cell towersHundreds of meters to kilometersFastCoarse in rural areas
IP address lookupCity or region levelFastCan be misleading behind VPNs
Typical location sources and accuracy

Setting enableHighAccuracy to true does not guarantee better results; it only asks the device to try harder. Indoors, it may simply cost more time and battery while returning a Wi-Fi-based estimate anyway.

Permissions, privacy and security rules

Location is sensitive personal data, so browsers protect the Geolocation API with several layers of control. A page can query the current state through the Permissions API without triggering a prompt, which allows a better explanation before the request.

  • Secure context only: the API works on HTTPS pages and localhost, not on plain HTTP.
  • User permission: the browser shows a prompt, and the decision may be remembered per origin.
  • Permissions Policy: embedded iframes need explicit geolocation permission from the embedding page.
  • Approximate location: some mobile platforms let users share only a coarse position, which shows up as a large accuracy radius.
  • Visible indicator: browsers display an icon while a site is using location.

Errors arrive as a GeolocationPositionError with one of three codes: 1 for permission denied, 2 for position unavailable and 3 for timeout. Robust code handles each code separately, because the right fallback differs.

Geolocation API compared with alternatives

The Geolocation API is not the only way to learn where a user is. Its combination of precision and consent distinguishes it from server-side methods.

MethodPrecisionUser consentTypical use
Geolocation APIMeters to kilometersExplicit promptMaps, delivery, nearby search
Server-side IP lookupCity or regionNone at the moment of lookupDefault language or currency
User-entered addressAs precise as typedImplicit in the inputCheckout and shipping
Native app locationMeters, also in backgroundOperating system promptNavigation and fitness apps
Ways to determine user location

A web page cannot track location in the background after it is closed, which separates browser geolocation from native applications. Continuous tracking with watchPosition() works only while the page stays open and, on many phones, only while it remains visible.

Good practice and common mistakes

The most common mistake is requesting location immediately on page load. Users who see a prompt without context often deny it, and a denial is usually remembered, so later requests fail silently. The better practice is to ask only after a clear user action, such as tapping a button labeled with the purpose.

Other pitfalls include omitting the timeout option, which can leave the interface waiting indefinitely, forgetting to call clearWatch() when tracking is no longer needed, and ignoring the accuracy value when deciding whether a position is good enough. A reliable implementation always offers a manual fallback, such as entering a postal code.

In plain words

The Geolocation API is how a website asks your browser where you are. Your browser first asks you for permission. If you agree, the site receives your approximate position on a map.

The site also learns how sure that answer is. Outdoors with a phone, it may know your location within a few meters. On a laptop, it may know only your neighborhood. You stay in control, because you can refuse or withdraw permission at any time.

A real-world example

A pharmacy chain’s website offers a button labeled “Find stores near me”. When a visitor taps it, the page calls getCurrentPosition() with a 10-second timeout and a maximumAge of five minutes, because store search does not need fresh, high-precision data.

On a phone, the result usually arrives within a second or two with an accuracy of about 30 meters, and the page lists the three nearest stores with opening hours. If the visitor denies permission or the request times out, the page falls back to a postal code field. Because the request happens only after a deliberate tap, far more visitors grant permission than they did when the old site asked immediately on load.