geolocation api 必须在 https 或 localhost 下调用,否则静默失败或抛 securityerror;error 回调覆盖多数场景,需按 code 分流处理;position.coords.accuracy 决定坐标可信度,>100 米应提示精度不足。

Geolocation API 调用前必须满足 HTTPS 或 localhost
浏览器只在安全上下文(secure context)中允许调用 navigator.geolocation,否则直接静默失败或抛出 SecurityError。本地开发时 http://localhost 和 http://127.0.0.1 是例外;但凡部署到真实域名,http://example.com 会立刻被拒绝。
- 检查控制台是否报错
Only secure origins are allowed—— 这是第一道拦路虎 - 用
location.protocol判断当前是否为https:,非 HTTPS 环境下提前提示用户或禁用定位按钮 - 某些老旧安卓 WebView(如 Android 6–8 的系统浏览器)即使 HTTPS 也可能不支持,需降级 fallback
getCurrentPosition 的 error 回调比 success 更常触发
用户点“允许”不等于定位成功。navigator.geolocation.getCurrentPosition(success, error, options) 的 error 回调实际覆盖绝大多数场景:用户拒接、GPS 关闭、超时、无信号、权限被系统级拦截(如 iOS 设置里关闭网站定位)。
-
error.code值比error.message更可靠:1(用户拒绝)、2(位置不可用)、3(超时,默认 10s) - 别依赖
error.message文本内容,不同浏览器/系统返回差异大,比如 Chrome 返回User denied geolocation prompt,Safari 可能返回空字符串 - 加
timeout和maximumAge参数很关键:{ timeout: 5000, maximumAge: 30000 }避免卡死,也防止复用过期坐标
position.coords 中的 accuracy 和 altitudeAccuracy 决定数据可用性
拿到 position 后,不能直接用 latitude/longitude 渲染地图或计算距离——得先看精度。WiFi 定位可能返回 accuracy: 65(米),而 GPS 在开阔地可能是 10,室内常见 1000+。
-
position.coords.accuracy是水平误差半径(单位:米),值越大越不可信;altitudeAccuracy同理,但多数设备不提供海拔 - 若
accuracy > 100,建议提示“定位精度较低,结果仅供参考”,或引导用户移至窗边/开启 GPS - 不要对
accuracy === null做任何假设——部分浏览器(如旧版 Firefox)不返回该字段,需用typeof position.coords.accuracy !== 'number'判断
watchPosition 不等于实时追踪,而是“变化时通知”
navigator.geolocation.watchPosition 不会持续轮询,它只在浏览器检测到坐标显著变化(由系统底层判断)或精度提升时才触发回调。因此不适合做车辆轨迹跟踪或高频更新 UI。
- 每次触发仍需检查
position.coords.accuracy,避免用低精度坐标覆盖高精度历史值 - 务必保存
watchId并在不需要时调用navigator.geolocation.clearWatch(watchId),否则内存泄漏且持续耗电 - 移动端后台切走后,大多数浏览器会暂停 watch,回到前台才恢复——别指望它在后台保持活跃
position 对象都得带精度校验,每个 error 都得按 code 分流,而不是只写一个弹窗提示“获取失败”。前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











