Geolocation API 是浏览器原生地理定位接口,需用户授权且仅在 HTTPS 或 localhost 中可用;支持单次获取(getCurrentPosition)和持续监听(watchPosition),需处理兼容性、错误及隐私限制。
Geolocation API 是浏览器原生支持的获取用户地理位置的接口,不需要额外库,但需要用户授权,且只在安全上下文(HTTPS 或 localhost)中可用。
调用 navigator.geolocation.getCurrentPosition() 即可请求当前经纬度。它接受两个回调函数:成功时执行第一个,失败时执行第二个。
position 对象,其中 position.coords.latitude 和 position.coords.longitude 是关键字段error 对象,error
.code 可判断原因(如 1=用户拒绝、2=位置不可用、3=超时){ enableHighAccuracy: true, timeout: 5000, maximumAge: 60000 }
用 navigator.geolocation.watchPosition() 替代单次获取,它返回一个唯一 ID,可用于后续停止监听。
navigator.geolocation.clearWatch(watchId) 释放资源maximumAge 和 timeout 控制精度与频率不是所有浏览器或环境都支持 Geolocation,需做兜底判断。
'geolocation' in navigator,避免 TypeError复制到 HTTPS 页面即可运行:
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
(pos) => {
const { latitude, longitude } = pos.coords;
console.log(`纬度:${latitude},经度:${longitude}`);
},
(err) => {
const msg = {
1: '您拒接了位置访问',
2: '设备无法获取位置信息',
3: '获取位置超时了'
}[err.code] || '未知错误';
alert('定位失败:' + msg);
},
{ timeout: 10000, enableHighAccuracy: false }
);
} else {
alert('您的浏览器不支持地理位置');
}
基本上就这些。用好 Geolocation API 的关键是尊重用户选择、做好降级处理、别盲目追求高精度。