---
title: Geolocation API:高精度定位与权限策略
keywords:
- navigator.geolocation
- getCurrentPosition
- watchPosition
- enableHighAccuracy
- timeout
description: 使用 Geolocation 进行定位与持续跟踪,合理设置精度与超时并处理权限与回退,提高体验与电量效率。
categories:
- 应用软件
- 编程开发
---
概述
Geolocation 提供当前位置与位置更新。通过选项控制精度与超时;在不支持或被拒绝时需提供回退方案。
用法/示例
navigator.geolocation.getCurrentPosition(
pos => console.log(pos.coords.latitude, pos.coords.longitude),
err => console.error(err),
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 60000 }
)
const id = navigator.geolocation.watchPosition(updateUI, console.error, { enableHighAccuracy: true })
// 停止跟踪
navigator.geolocation.clearWatch(id)
工程建议
- 权衡精度与能耗,移动端谨慎开启高精度;设置
timeout与maximumAge改善体验。 - 明确权限文案与用途,遵守隐私政策;对拒绝场景提供城市级或手动定位。
- 缓存最后位置用于初始化与离线降级。
参考与验证
- MDN:Geolocation — https://developer.mozilla.org/docs/Web/API/Geolocation_API

发表评论 取消回复