地理定位:getCurrentPosition() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

安全上下文: 此功能僅在安全上下文(HTTPS)中可用,且支援此功能的瀏覽器數量有限。

Geolocation 介面的 getCurrentPosition() 方法用於獲取裝置的當前位置。

請注意,除了需要安全上下文外,此功能還可能被 Permissions-Policygeolocation 選項阻止,並且還需要使用者明確授予許可權。如果需要,呼叫此方法時將提示使用者。可以使用 Permissions API 中的 geolocation 使用者許可權查詢許可權狀態。

語法

js
getCurrentPosition(success)
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)

引數

success

一個回撥函式,它接受一個 GeolocationPosition 物件作為其唯一的輸入引數。

error 可選

一個可選的回撥函式,它接受一個 GeolocationPositionError 物件作為其唯一的輸入引數。

options 可選

一個可選物件,包含以下引數

maximumAge 可選

一個正整數,表示可接受的快取位置的最大年齡(以毫秒為單位)。如果設定為 0,則表示裝置不能使用快取的位置,必須嘗試獲取實際的當前位置。如果設定為 Infinity,則裝置必須返回快取的位置,無論其年齡如何。預設值:0

timeout 可選

一個正整數,表示裝置允許花費的最大時間(以毫秒為單位)來返回位置。預設值為 Infinity,這意味著 getCurrentPosition() 直到位置可用才會返回。

enableHighAccuracy 可選

一個布林值,指示應用程式希望獲得最佳結果。如果為 true 且裝置能夠提供更精確的位置,它將這樣做。請注意,這可能導致響應時間變慢或功耗增加(例如,在移動裝置上使用 GPS 晶片)。另一方面,如果為 false,裝置可以自由地透過更快地響應和/或使用更少的電量來節省資源。預設值:false

返回值

無(undefined)。

示例

js
const options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0,
};

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

  console.log("Your current position is:");
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

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

navigator.geolocation.getCurrentPosition(success, error, options);

規範

規範
Geolocation
# getcurrentposition-method

瀏覽器相容性

另見