地理定位: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()