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

浏览器兼容性

另见