地理定位:watchPosition() 方法
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 |
浏览器兼容性
加载中…
另见
- 使用 Geolocation API
- 它所属的接口
Geolocation,以及访问它的方式 —Navigator.geolocation。 - 相反的操作:
Geolocation.clearWatch() - 类似的方法:
Geolocation.getCurrentPosition()