# Geolocation API

> Geolocation methods, options, permission states, error codes, feature detection, and recovery paths for denied or unavailable position requests.

`navigator.geolocation` is the entry point for retrieving a device's geographic position. Call `getCurrentPosition()` for one result or `watchPosition()` for updates, and receive positions or failures through callbacks.

BCD `api.Geolocation` records support from Chrome 5, Edge 12, Firefox 3.5, and Safari 5 (iOS 3). BCD `api.Geolocation.secure_context_required` records the secure-context requirement from Chrome 50, Firefox 55, and Safari 10. The secure-context rules treat `http://` as non-secure in general, while `localhost` can be potentially trustworthy. The [Geolocation browser support](/compatibility/geolocation/) page exposes the corresponding compatibility dataset.

## Syntax

```js
navigator.geolocation.getCurrentPosition(successCallback)
navigator.geolocation.getCurrentPosition(successCallback, errorCallback)
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)

navigator.geolocation.watchPosition(successCallback)
navigator.geolocation.watchPosition(successCallback, errorCallback)
navigator.geolocation.watchPosition(successCallback, errorCallback, options)

navigator.geolocation.clearWatch(watchId)
```

`getCurrentPosition()` returns `undefined`. `watchPosition()` returns an implementation-defined positive `long` id, which `clearWatch(watchId)` removes from the active watch list. If the associated document is not fully active, the specification requires `watchPosition()` to queue `POSITION_UNAVAILABLE` for a supplied error callback and return `0`.

A watch waits for a significant position change, whose definition is left to the implementation. User agents may rate-limit reports. Updates are delivered while the document is fully active and visible; delivery resumes after the document becomes fully active and visible again. Call `clearWatch()` with the returned id to stop the watch.

## Parameters

Both request methods accept the same callbacks and options.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `successCallback` | `PositionCallback` | Yes | Receives a `GeolocationPosition` containing `coords` (a `GeolocationCoordinates`) and the acquisition `timestamp` (an `EpochTimeStamp`). |
| `errorCallback` | `PositionErrorCallback?` | No | Receives a `GeolocationPositionError` with `code` and `message`. If it is `null`, the specification's error-callback algorithm returns without invoking a callback. |
| `options` | `PositionOptions` | No | Controls accuracy, acquisition timeout, and use of a cached position. |

`PositionOptions` contains the following optional members.

| Member | Type | Default | Description |
|---|---|---|---|
| `enableHighAccuracy` | `boolean` | `false` | Hints that the application wants the most accurate available result. The specification warns that this can take longer or consume more power, and that the device may not produce a more accurate result. |
| `timeout` | `[Clamp] unsigned long` | `0xFFFFFFFF` ms | Limits position acquisition. Time spent waiting for visibility or permission is excluded; `0` can cause an immediate timeout. |
| `maximumAge` | `[Clamp] unsigned long` | `0` ms | Accepts a cached position no older than this value. A cached result is eligible only when its recorded `[[isHighAccuracy]]` flag matches `enableHighAccuracy`. |

`coords.latitude` and `coords.longitude` use WGS84 degrees. `coords.accuracy` is a radius in metres at the 68% confidence level (one standard deviation). Altitude, altitude accuracy, heading, and speed can be `null` when the system does not supply them. BCD records `GeolocationCoordinates.toJSON()` from Chrome 126, Firefox 129, and Safari 18.

## Exceptions

The methods report failures to `errorCallback` with a `GeolocationPositionError`; they do not use thrown exceptions for the acquisition outcomes defined by the Geolocation specification.

| `code` | Constant | Specified condition |
|---|---|---|
| `1` | `PERMISSION_DENIED` | The user or system denies permission, the document is not allowed to use the `geolocation` policy-controlled feature, or the request comes from a non-secure context. |
| `2` | `POSITION_UNAVAILABLE` | The document is not fully active, position acquisition fails, or another acquisition error occurs. |
| `3` | `TIMEOUT` | The acquisition time exceeds `options.timeout`. |

Browser permission and operating-system permission are separate. The specification notes that a browser-level grant can coexist with an operating-system denial of location services; that acquisition follows the user-or-system-denied failure path.

Permission state is not a permanent diagnostic. The Permissions specification defines `granted`, `prompt`, and `denied`, and allows permission lifetimes to vary by user agent. When a lifetime expires, the state returns to its default, such as `prompt`. Geolocation permission can be offered for a session or for one day, so a later request can ask the user again after the stored decision expires.

Permissions Policy is checked before the permission prompt. Geolocation's default allowlist is `'self'`; a cross-origin frame needs delegation such as `allow="geolocation"`, while `Permissions-Policy: geolocation=()` disables the feature for the document and its descendants.

The specification leaves `GeolocationPositionError.message` as developer-facing, implementation-defined text. Chromium defines `User denied Geolocation` for a permission denial and `Geolocation has been disabled in this document by permissions policy.` for a policy denial; applications should branch on `code` instead of matching either string.

:::caution
Chromium's [`geolocation.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/core/geolocation/geolocation.cc) (chromium.googlesource.com) records a `[Violation]` and defines the discouraged-API message `Only request geolocation information in response to a user gesture.` for a request without transient user activation. The same source defines `Geolocation access has been blocked because of a permissions policy applied to the current document. See https://crbug.com/414348233 for more details.` for a policy block and reports `PERMISSION_DENIED` with code `1`.
:::

## Examples

Request location after a reader action, handle all acquisition failures, and keep a route that works without the API. The examples use a manual location field as that recovery route.

### Requesting one position with manual entry

Save this complete document as `geolocation-demo.html`, then serve it over HTTPS or from a potentially trustworthy local origin such as `http://localhost`. Click **Use my location**: success prints the coordinates and accuracy, while a missing API, denied permission, unavailable position, or timeout reveals a working city form. Submitting the form prints the manually entered city, so the recovery path remains usable without geolocation.

```html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Geolocation with manual fallback</title>
<button id="use-location" type="button">Use my location</button>
<form id="manual" hidden>
  <label>City <input id="city" required autocomplete="address-level2"></label>
  <button>Use this city</button>
</form>
<output id="result" aria-live="polite">Choose a location method.</output>
<script>
  const locateButton = document.querySelector("#use-location");
  const manualForm = document.querySelector("#manual");
  const cityField = document.querySelector("#city");
  const result = document.querySelector("#result");

  function useManualEntry(reason) {
    result.textContent = `${reason}. Enter a city instead.`;
    manualForm.hidden = false;
    cityField.focus();
  }

  manualForm.addEventListener("submit", (event) => {
    event.preventDefault();
    result.textContent = `Using manually entered city: ${cityField.value}`;
  });

  locateButton.addEventListener("click", () => {
    if (!("geolocation" in navigator)) {
      useManualEntry("Geolocation is unavailable");
      return;
    }
    result.textContent = "Requesting location...";
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        result.textContent = `Latitude ${coords.latitude}, longitude ${coords.longitude}, accuracy radius ${coords.accuracy} m`;
      },
      ({ code }) => {
        const reason = code === 1 ? "Location access denied"
          : code === 2 ? "Location unavailable" : "Location request timed out";
        useManualEntry(reason);
      },
      { enableHighAccuracy: false, timeout: 10_000, maximumAge: 60_000 },
    );
  });
</script>
</html>
```

The visible output starts with `Choose a location method.` and changes after either path completes. The failure branch uses application-controlled text instead of exposing the browser's implementation-defined error message.

### Connecting a request to an existing address field

When the surrounding application already supplies `showNearby()`, this focused handler reveals its address field for an unsupported API or any acquisition error. The inline feature test is `"geolocation" in navigator`.

```js
const addressField = document.querySelector("#address");

function useManualEntry(reason) {
  addressField.hidden = false;
  addressField.placeholder = reason;
}

document.querySelector("#use-location").addEventListener("click", () => {
  if (!("geolocation" in navigator)) {
    useManualEntry("Enter your city");
    return;
  }
  navigator.geolocation.getCurrentPosition(
    ({ coords }) => {
      showNearby(coords.latitude, coords.longitude, coords.accuracy);
    },
    (error) => {
      const reasons = { 1: "Location access denied", 2: "Location unavailable", 3: "Location timed out" };
      useManualEntry(reasons[error.code] ?? error.message);
    },
    { enableHighAccuracy: false, timeout: 10_000, maximumAge: 60_000 },
  );
});
```

This shorter integration fragment uses the same manual-entry recovery as the complete document; `showNearby()` remains an application-supplied rendering function.

### Stopping a watch after an error

A watch can update a map until the view closes. Store the id returned by `watchPosition()`, clear it after an acquisition error, and clear it on `pagehide` when navigating away. Switching tabs alone does not trigger this cleanup.

```js
let watchId = null;

function startTracking(onMove) {
  if (!("geolocation" in navigator)) return false;
  watchId = navigator.geolocation.watchPosition(
    (position) => onMove(position.coords),
    (error) => {
      stopTracking();
      console.warn(`Tracking stopped: ${error.code} ${error.message}`);
    },
    { enableHighAccuracy: true, maximumAge: 0 },
  );
  return watchId !== 0;
}

function stopTracking() {
  if (watchId !== null) navigator.geolocation.clearWatch(watchId);
  watchId = null;
}

document.querySelector("#start").addEventListener("click", () => startTracking(updateMap));
document.querySelector("#stop").addEventListener("click", stopTracking);
window.addEventListener("pagehide", stopTracking);
```

For a non-fully-active document, the method queues the `POSITION_UNAVAILABLE` error callback and synchronously returns `0`; the queued callback runs later. This helper returns `false` for that synchronous signal, while its supplied error callback logs the asynchronous failure and stops tracking; the caller can use the return value to open a manual route form.

### Diagnosing context, policy, and permission

`window.isSecureContext` identifies the secure-context layer, `navigator.permissions.query()` reads the permission state without requesting it, and the position callback supplies the acquisition result.

```js
async function diagnoseGeolocation(report) {
  if (!window.isSecureContext) {
    report("Use HTTPS or a potentially trustworthy local origin");
    return;
  }
  if (!("geolocation" in navigator)) {
    report("Geolocation is not exposed in this browser");
    return;
  }

  if (navigator.permissions) {
    const status = await navigator.permissions.query({ name: "geolocation" });
    report(`Permission state: ${status.state}`);
  }

  navigator.geolocation.getCurrentPosition(
    ({ coords }) => report(`Accuracy radius: ${coords.accuracy} m`),
    ({ code, message }) => report(`Geolocation error ${code}: ${message}`),
    { timeout: 10_000, maximumAge: 0 },
  );
}

document.querySelector("#diagnose").addEventListener("click", () => {
  diagnoseGeolocation((line) => appendDiagnosticLine(line));
});
```

A `denied` state does not distinguish a user decision from a Permissions Policy restriction, because policy can prevent a document from requesting express permission. Inspect the response's `Permissions-Policy` header and the embedding iframe's `allow` attribute when code `1` persists. Code `2` points to document activity or acquisition, while code `3` points to the configured timeout.

### Continuing after an unsupported permission query

The Permissions specification makes `query()` reject with `TypeError` when the permission name is unsupported. Wrap that optional diagnostic so a rejected query does not prevent the application from requesting a position and using its error callback.

```js
async function readGeolocationPermission(report) {
  if (!navigator.permissions) {
    report("Permissions API unavailable");
    return null;
  }
  try {
    const status = await navigator.permissions.query({ name: "geolocation" });
    report(`Permission state: ${status.state}`);
    return status.state;
  } catch (error) {
    report(`Permission query unavailable: ${error.name}`);
    return null;
  }
}
```

A `null` result means the preflight did not produce a state. Keep `getCurrentPosition()` and its success and error callbacks on the user-action path; the permission query does not acquire a position.

### Setting button state from permission status

Where `navigator.permissions` is available, `navigator.permissions.query({ name: "geolocation" })` can read the state before a position request. This helper returns `"unknown"` when that API is absent, leaving the click handler responsible for requesting a position and handling the error.

```js
async function locationButtonState() {
  if (!("geolocation" in navigator)) return "unsupported";
  if (!navigator.permissions) return "unknown"; // request on click and handle the error
  const { state } = await navigator.permissions.query({ name: "geolocation" });
  return state; // "granted" | "prompt" | "denied"
}

const state = await locationButtonState();
document.querySelector("#use-location").hidden = state === "unsupported" || state === "denied";
document.querySelector("#denied-help").hidden = state !== "denied";
```

Keep the request and its error callback on the button's click path because a reported permission state is not an acquisition result.

## Correction (2026-11-18)

This revision corrects three previously published statements: `coords.accuracy` uses a 68% confidence level, not 95%; permission lifetimes can expire and return to their default state rather than necessarily lasting until a manual settings change; and `watchPosition()` queues `POSITION_UNAVAILABLE` for a supplied error callback before returning `0` when the document is not fully active.

## See also

- [Geolocation browser support](/compatibility/geolocation/), the compatibility dataset for `api.Geolocation`
- [The notification permission model](/reference/notifications/permissions/), another API using `granted`, `prompt`, and `denied`
- [Generic Sensor API](/reference/capabilities/sensors/), orientation and motion sensor interfaces
- [Local Network Access](/reference/capabilities/local-network-access/), another permission-gated capability
- [Geolocation API: getCurrentPosition() method](https://www.w3.org/TR/geolocation/#getcurrentposition-method) (w3.org)
- [Permissions](https://www.w3.org/TR/permissions/) (w3.org)
- [Permissions Policy](https://w3c.github.io/webappsec-permissions-policy/) (w3c.github.io)