Geolocation API 仅在 HTTPS 或 localhost 下可用,HTTP 协议下直接报错;必须显式传入 success 和 error 回调;enableHighAccuracy=true 可能导致超时或失败;watchPosition 需手动 clearWatch 防泄漏。

Geolocation API 不支持 HTTPS 时直接报错
浏览器只允许在安全上下文(即 HTTPS 或 localhost)中调用 navigator.geolocation。如果你在 HTTP 协议下开发,getCurrentPosition 会立刻触发 error 回调,error.code 通常是 1(PERMISSION_DENIED),但实际原因是协议不被允许——不是用户拒绝,而是浏览器根本禁止启动。
实操建议:
- 本地开发用
http://localhost:3000或http://127.0.0.1:8080可以正常调用 - 部署到线上必须使用 HTTPS,自签名证书也不行(Chrome 会拦截)
- 不要依赖
error.message判断是否被拒,优先检查当前协议:location.protocol === 'https:'
getCurrentPosition 的 success 和 error 回调必须显式传入
navigator.geolocation.getCurrentPosition 是一个“老式”异步 API,不返回 Promise,也不能 await。如果只传 success 回调,出错时页面静默失败,很难定位问题。
常见错误现象:位置没拿到、控制台无报错、console.log 也没执行——大概率是漏写了 error 参数,导致异常被吞掉。
立即学习“Java免费学习笔记(深入)”;
实操建议:
- 始终传入两个回调:
getCurrentPosition(success, error, options) - 在
error回调里至少打印error.code和error.message - 想用
async/await?自己封装成 Promise:
function getPosition() {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(
pos => resolve(pos),
err => reject(err),
{ enableHighAccuracy: true, timeout: 5000 }
);
});
}
// 然后可以:
// try {
// const pos = await getPosition();
// console.log(pos.coords.latitude, pos.coords.longitude);
// } catch (err) {
// console.error('获取位置失败:', err.code, err.message);
// }
enableHighAccuracy 设为 true 可能反而更慢或失败
enableHighAccuracy: true 会强制设备启用 GPS(而非仅用 WiFi / 基站估算),在手机上可能触发系统级权限弹窗、等待更久,甚至在室内无 GPS 信号时永远超时。
使用场景差异:
- 打车、导航类应用:需要米级精度,可设为
true,但务必配timeout和maximumAge - 城市级推荐(如“附近餐厅”):默认值(
false)足够,响应更快,兼容性更好 - 后台轻量上报:建议加
maximumAge: 300000(5 分钟),避免重复定位耗电
注意:timeout 是指整个定位过程的上限时间,不是网络请求超时;若设太短(如 1000),GPS 启动都来不及,必走 error 分支。
watchPosition 返回的是监听 ID,必须手动清除
navigator.geolocation.watchPosition 会持续监听位置变化,返回一个数字 ID。它不会自动停止,即使页面跳转、组件卸载,监听仍在后台运行——造成内存泄漏、电量消耗、甚至跨页面重复触发。
容易踩的坑:
- React 中在
useEffect里调用watchPosition,但没保存 ID 或没在清理函数中调用clearWatch - Vue 里
mounted开启监听,beforeUnmount忘记清除 - 单页应用路由切换后,旧监听还在跑
正确做法:始终保存 ID,并在适当生命周期结束时清除:
let watchId;
function startWatching() {
watchId = navigator.geolocation.watchPosition(
pos => console.log(pos.coords),
err => console.error(err),
{ maximumAge: 30000 }
);
}
function stopWatching() {
if (watchId !== undefined) {
navigator.geolocation.clearWatch(watchId);
watchId = undefined;
}
}
高精度定位和持续监听都是耗资源操作,别默认开启;用户没明确触发前,先用一次 getCurrentPosition 获取快照更稳妥。











