# Geolocation API

> Geolocation API 的方法、选项、权限状态、错误码，以及定位请求被拒绝或失败时的检测与回退。

`navigator.geolocation` 是获取设备地理位置的入口。调用 `getCurrentPosition()` 获取一次结果，调用 `watchPosition()` 接收后续更新；位置和错误都由回调异步送达。

BCD `api.Geolocation` 记载 Chrome 5、Edge 12、Firefox 3.5 和 Safari 5（iOS 3）开始支持。BCD `api.Geolocation.secure_context_required` 记载安全上下文要求从 Chrome 50、Firefox 55 和 Safari 10 开始实施。安全上下文规则通常把 `http://` 视为非安全来源，`localhost` 则可能被视为可信来源。[Geolocation 浏览器支持](/zh/compatibility/geolocation/)列出了对应的兼容性数据。

## 语法

```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()` 返回 `undefined`。`watchPosition()` 返回由实现决定的大于零的 `long` id，`clearWatch(watchId)` 会从活动监视列表中移除这个 id。关联文档不是 fully active 时，规范要求 `watchPosition()` 为已提供的错误回调排入 `POSITION_UNAVAILABLE`，随后返回 `0`。

监视会等待实现认定的显著位置变化，规范允许浏览器限制报告频率。文档 fully active 且可见时才交付更新；文档恢复为 fully active 和可见后，更新也会恢复。把返回的 id 传给 `clearWatch()` 即可停止监视。

## 参数

两个请求方法接受相同的回调与选项。

| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| `successCallback` | `PositionCallback` | 是 | 接收 `GeolocationPosition`，其中含 `coords`（`GeolocationCoordinates`）和获取位置时的 `timestamp`（`EpochTimeStamp`）。 |
| `errorCallback` | `PositionErrorCallback?` | 否 | 接收带 `code` 和 `message` 的 `GeolocationPositionError`。值为 `null` 时，规范的错误回调算法直接返回。 |
| `options` | `PositionOptions` | 否 | 控制精度、获取位置的超时和缓存位置的使用。 |

`PositionOptions` 的成员都可省略。

| 成员 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| `enableHighAccuracy` | `boolean` | `false` | 提示应用需要可得的最精确结果。规范警告，高精度可能延长响应时间或增加耗电，设备也可能无法给出更精确的结果。 |
| `timeout` | `[Clamp] unsigned long` | `0xFFFFFFFF` 毫秒 | 限制获取位置所用的时间。等待文档可见和等待权限的时间不计算在内；设为 `0` 可能立即超时。 |
| `maximumAge` | `[Clamp] unsigned long` | `0` 毫秒 | 接受不早于这个值的缓存位置。缓存结果记录的 `[[isHighAccuracy]]` 标志还需与 `enableHighAccuracy` 相同。 |

`coords.latitude` 和 `coords.longitude` 使用 WGS84 角度。`coords.accuracy` 是以米计的半径，对应 68% 置信水平（一个标准差）。系统没有提供数据时，海拔、海拔精度、航向和速度可以是 `null`。BCD 记载 `GeolocationCoordinates.toJSON()` 从 Chrome 126、Firefox 129 和 Safari 18 开始支持。

## 异常

Geolocation 规范定义的定位失败不会以异常抛出。两个方法把 `GeolocationPositionError` 交给 `errorCallback`。

| `code` | 常量 | 规范定义的条件 |
|---|---|---|
| `1` | `PERMISSION_DENIED` | 用户或系统拒绝权限；文档不允许使用由策略控制的 `geolocation` 特性；或者请求来自非安全上下文。 |
| `2` | `POSITION_UNAVAILABLE` | 文档不是 fully active；无法获取位置；或者获取过程中出现其他错误。 |
| `3` | `TIMEOUT` | 获取位置的时间超过 `options.timeout`。 |

浏览器权限与操作系统权限互相独立。规范指出，用户可能已经在浏览器中授权，但操作系统仍禁止位置服务；这类获取失败走用户或系统拒绝的处理分支。

权限状态不能当作永久结论。Permissions 规范定义了 `granted`、`prompt` 和 `denied`，权限寿命由浏览器决定。寿命到期后，状态回到 `prompt` 等默认值。Geolocation 权限可能只授予一个会话或一天，因此已保存的决定到期后，后续请求可以再次询问用户。

浏览器会先检查 Permissions Policy，再决定能否请求用户授权。Geolocation 的默认允许列表是 `'self'`；跨源 iframe 需要用 `allow="geolocation"` 等方式委派。`Permissions-Policy: geolocation=()` 会为文档及其后代停用这项特性。

规范把 `GeolocationPositionError.message` 留给浏览器生成，文本供开发者查看。Chromium 为权限拒绝定义了 `User denied Geolocation`，为策略拒绝定义了 `Geolocation has been disabled in this document by permissions policy.`；应用应根据 `code` 分支，不要匹配这两段文字。

:::caution
Chromium 的 [`geolocation.cc`](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/core/geolocation/geolocation.cc)（chromium.googlesource.com）会记录 `[Violation]`，并为缺少瞬时用户激活的请求定义提示 `Only request geolocation information in response to a user gesture.`。同一文件为策略拦截定义了 `Geolocation access has been blocked because of a permissions policy applied to the current document. See https://crbug.com/414348233 for more details.`，并报告 `PERMISSION_DENIED`，错误码为 `1`。
:::

## 示例

在读者操作后请求位置，处理所有获取失败，并保留不依赖 API 的可用路径。下面以手动填写位置作为回退方案。

### 获取一次位置，失败后允许手动输入

把下面的完整文档保存为 `geolocation-demo.html`，再通过 HTTPS 或 `http://localhost` 等可信本地来源提供。点击“使用我的位置”后，成功时会显示坐标与精度；API 不存在、权限被拒绝、位置不可用或请求超时时，则显示可提交的城市表单。提交表单后会显示手动输入的城市，因此没有定位能力时仍可走完回退路径。

```html
<!doctype html>
<html lang="zh-CN">
<meta charset="utf-8">
<title>带手动回退的定位示例</title>
<button id="use-location" type="button">使用我的位置</button>
<form id="manual" hidden>
  <label>城市 <input id="city" required autocomplete="address-level2"></label>
  <button>使用这个城市</button>
</form>
<output id="result" aria-live="polite">请选择位置输入方式。</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}，请改为输入城市。`;
    manualForm.hidden = false;
    cityField.focus();
  }

  manualForm.addEventListener("submit", (event) => {
    event.preventDefault();
    result.textContent = `使用手动输入的城市：${cityField.value}`;
  });

  locateButton.addEventListener("click", () => {
    if (!("geolocation" in navigator)) {
      useManualEntry("此浏览器无法定位");
      return;
    }
    result.textContent = "正在请求位置……";
    navigator.geolocation.getCurrentPosition(
      ({ coords }) => {
        result.textContent = `纬度 ${coords.latitude}，经度 ${coords.longitude}，精度半径 ${coords.accuracy} 米`;
      },
      ({ code }) => {
        const reason = code === 1 ? "位置权限被拒绝"
          : code === 2 ? "无法获取位置" : "定位请求超时";
        useManualEntry(reason);
      },
      { enableHighAccuracy: false, timeout: 10_000, maximumAge: 60_000 },
    );
  });
</script>
</html>
```

页面初始显示“请选择位置输入方式。”，任一路径完成后都会更新这段可见输出。失败分支使用应用控制的文字，不会显示由浏览器实现决定的错误消息。

### 接入已有的地址输入框

如果应用已经提供 `showNearby()`，下面的处理器会在 API 不存在或获取位置失败时显示地址输入框。行内的能力检测写作 `"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("请输入所在城市");
    return;
  }
  navigator.geolocation.getCurrentPosition(
    ({ coords }) => {
      showNearby(coords.latitude, coords.longitude, coords.accuracy);
    },
    (error) => {
      const reasons = { 1: "位置权限被拒绝", 2: "无法获取位置", 3: "定位超时" };
      useManualEntry(reasons[error.code] ?? error.message);
    },
    { enableHighAccuracy: false, timeout: 10_000, maximumAge: 60_000 },
  );
});
```

这个精简片段沿用完整示例的手动输入回退；`showNearby()` 仍由应用负责实现和渲染。

### 定位失败后停止监视

监视可以持续更新地图，直到视图关闭。保存 `watchPosition()` 返回的 id；获取位置失败时清除监视，导航离开页面触发 `pagehide` 时也清除监视。仅切换标签页不会触发这段清理代码。

```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(`跟踪已停止：${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);
```

关联文档不是 fully active 时，规范规定的顺序是：异步回调 `POSITION_UNAVAILABLE`，同步返回 `0`。排入的错误回调稍后才执行。辅助函数遇到同步信号时返回 `false`，已提供的错误回调则记录异步失败并停止监视；调用方可以根据返回值打开手动路线表单。

### 依次排查上下文、策略与权限

`window.isSecureContext` 判断安全上下文，`navigator.permissions.query()` 读取权限状态但不发起请求，位置回调则给出获取结果。

```js
async function diagnoseGeolocation(report) {
  if (!window.isSecureContext) {
    report("请使用 HTTPS 或可信的本地来源");
    return;
  }
  if (!("geolocation" in navigator)) {
    report("此浏览器未暴露 Geolocation API");
    return;
  }

  if (navigator.permissions) {
    const status = await navigator.permissions.query({ name: "geolocation" });
    report(`权限状态：${status.state}`);
  }

  navigator.geolocation.getCurrentPosition(
    ({ coords }) => report(`精度半径：${coords.accuracy} 米`),
    ({ code, message }) => report(`定位错误 ${code}：${message}`),
    { timeout: 10_000, maximumAge: 0 },
  );
}

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

`denied` 无法区分用户决定和 Permissions Policy 限制，因为策略可以让文档失去请求明确授权的资格。错误码 `1` 持续出现时，检查响应的 `Permissions-Policy` 标头和外层 iframe 的 `allow` 属性。错误码 `2` 指向文档活动状态或位置获取，错误码 `3` 指向设定的超时时间。

### 权限查询不受支持时继续定位

Permissions 规范规定，不支持权限名称时，`query()` 以 `TypeError` 拒绝。用下面的辅助函数包住这项可选诊断；查询失败后，应用仍可请求位置，并使用它的错误回调。

```js
async function readGeolocationPermission(report) {
  if (!navigator.permissions) {
    report("Permissions API 不可用");
    return null;
  }
  try {
    const status = await navigator.permissions.query({ name: "geolocation" });
    report(`权限状态：${status.state}`);
    return status.state;
  } catch (error) {
    report(`无法查询权限：${error.name}`);
    return null;
  }
}
```

结果为 `null` 表示预检没有读到状态。仍要在用户操作路径中调用 `getCurrentPosition()`，并保留成功与错误回调；权限查询本身不会获取位置。

### 根据权限状态设置按钮

存在 `navigator.permissions` 时，`navigator.permissions.query({ name: "geolocation" })` 可以在请求位置前读取权限状态。没有这项 API 时，辅助函数返回 `"unknown"`，点击处理器仍需发起位置请求并处理错误。

```js
async function locationButtonState() {
  if (!("geolocation" in navigator)) return "unsupported";
  if (!navigator.permissions) return "unknown"; // 点击时再请求并处理错误
  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";
```

权限状态不是位置获取结果，因此按钮的点击路径仍需保留请求与错误回调。

## 更正（2026-11-18）

本次修订更正了三项已发布陈述：`coords.accuracy` 使用 68% 而非 95% 置信水平；权限寿命可能到期并回到默认状态，并非必然持续到用户手动修改设置；文档不是 fully active 时，`watchPosition()` 会先为已提供的错误回调排入 `POSITION_UNAVAILABLE`，再返回 `0`。

## 另请参阅

- [Geolocation 浏览器支持](/zh/compatibility/geolocation/)，`api.Geolocation` 的兼容性数据
- [通知权限模型](/zh/reference/notifications/permissions/)，另一项使用 `granted`、`prompt` 和 `denied` 的 API
- [Generic Sensor API 通用传感器](/zh/reference/capabilities/sensors/)，朝向与运动传感器接口
- [本地网络访问](/zh/reference/capabilities/local-network-access/)，另一项受权限控制的能力
- [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）