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

瀏覽器相容性

另見