地理定位:watchPosition() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

安全上下文: 此功能仅在安全上下文(HTTPS)中可用,且支持此功能的浏览器数量有限。

Geolocation 接口的 watchPosition() 方法用于注册一个处理程序函数,该函数将在设备的位置每次发生变化时自动调用。您还可以选择性地指定一个错误处理回调函数。

请注意,除了需要安全上下文外,此功能还可能被 geolocation Permissions-Policy 阻止,并且还需要用户明确授予权限。如果需要,调用此方法时将提示用户。可以使用 Permissions API 中的 geolocation 用户权限查询权限状态。

语法

js
watchPosition(success)
watchPosition(success, error)
watchPosition(success, error, options)

参数

success

一个接受 GeolocationPosition 对象作为输入参数的回调函数。

error 可选

一个接受 GeolocationPositionError 对象作为输入参数的可选回调函数。

options 可选

一个可选对象,提供位置监视的配置选项。有关可能选项的更多详细信息,请参阅 Geolocation.getCurrentPosition()

返回值

一个标识已注册处理程序的整数 ID。该 ID 可以传递给 Geolocation.clearWatch() 以取消注册处理程序。

示例

js
let id;
let target;
let options;

function success(pos) {
  const crd = pos.coords;

  if (target.latitude === crd.latitude && target.longitude === crd.longitude) {
    console.log("Congratulations, you reached the target");
    navigator.geolocation.clearWatch(id);
  }
}

function error(err) {
  console.error(`ERROR(${err.code}): ${err.message}`);
}

target = {
  latitude: 0,
  longitude: 0,
};

options = {
  enableHighAccuracy: false,
  timeout: 5000,
  maximumAge: 0,
};

id = navigator.geolocation.watchPosition(success, error, options);

规范

规范
Geolocation
# watchposition-method

浏览器兼容性

另见