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

成功得到位置信息时的回调函数,使用Position 对象作为唯一的参数。

error 可选

获取位置信息失败时的回调函数,使用 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

请参考