Geolocation.getCurrentPosition()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Geolocation.getCurrentPosition() 方法用來獲取設備當前的位置。

語法

navigator.geolocation.getCurrentPosition(success[, error[, options]])

參數

success

一個回呼函式(callback function) 會被傳入一個Position 的物件。

error 選擇性

一個選擇性的錯誤回呼函式(callback function),會被傳入一個 PositionError 的物件。

options 選擇性

一個選擇性的 PositionOptions 的物件。

範例

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

function success(pos) {
  var 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);

規格

Specification
Geolocation
# getcurrentposition-method

瀏覽器的相容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
getCurrentPosition

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

請參考