HTML5 地理定位:从“问一句”到“拿到坐标”的全流程
72
0
0
一句话:浏览器自带 GPS,只要你 HTTPS + 用户点头,就能拿经纬度。下面给你“能跑”的代码 + “能防”的坑,复制即可上线。
1. 先判断浏览器给不给面子
if ('geolocation' in navigator) {
console.log('定位可用');
} else {
alert('您的浏览器不支持地理定位');
}- 不支持的大多是古董 IE,直接走备用方案(IP 定位或手动选择城市)。
2. 一次问坐标:getCurrentPosition()
navigator.geolocation.getCurrentPosition(
success => {
const lat = success.coords.latitude; // 纬度
const lon = success.coords.longitude; // 经度
const acc = success.coords.accuracy; // 精度(米)
console.log(`你就在 ${lat}, ${lon} 左右,误差 ${acc} 米`);
},
err => {
switch (err.code) {
case err.PERMISSION_DENIED:
alert('您拒绝了定位请求'); break;
case err.POSITION_UNAVAILABLE:
alert('暂时拿不到位置'); break;
case err.TIMEOUT:
alert('定位超时'); break;
default:
alert('未知错误'); break;
}
},
{
enableHighAccuracy: true, // 尽量用 GPS
timeout: 5000, // 5 秒算超时
maximumAge: 0 // 不用缓存
}
);- 第三个参数可选,但强烈建议加上,否则移动端可能一直用缓存坐标。
3. 持续追坐标:watchPosition() & 停表
const watchId = navigator.geolocation.watchPosition(
pos => console.log('新坐标:', pos.coords.latitude, pos.coords.longitude),
err => console.error('追坐标失败', err)
);
// 以后不想追了
navigator.geolocation.clearWatch(watchId);- 适合导航、运动类场景;记得在页面卸载前
clearWatch,省电。
4. 浏览器到底怎么算出你在哪?
| 技术 | 精度 | 场景 | 备注 |
|---|---|---|---|
| GPS | ±5 m | 户外、手机 | 最准,但耗电 |
| Wi-Fi/基站 | ±50-100 m | 室内、城市 | 有网就能用 |
| IP 地址 | 城市级 | 备用 | 误差大,常被当“降级方案” |
最终用谁浏览器说了算,咱们只负责调 API。
5. 实战:一键定位 + 地图钉一下
<button id="locate">定位我</button>
<div id="map" style="height:300px; background:#f5f5f5;"></div>
<script>
document.getElementById('locate').onclick = () => {
if (!('geolocation' in navigator)) return alert('浏览器不支持');
navigator.geolocation.getCurrentPosition(
pos => {
const {latitude: lat, longitude: lon, accuracy: acc} = pos.coords;
// 这里用任意地图 API 钉坐标,下面以百度为例
const map = new BMap.Map('map');
const point = new BMap.Point(lon, lat);
map.centerAndZoom(point, 17);
map.addOverlay(new BMap.Marker(point));
map.addOverlay(new BMap.Circle(point, acc, {strokeColor: 'blue', fillOpacity: 0.2}));
},
err => alert(`定位失败:${err.message}`)
);
};
</script>
<script src="https://api.map.baidu.com/api?v=3.0&ak=你的密钥"></script>- 高德/腾讯/谷歌写法同理,只要把
lat/lon丢进去即可。
6. 常见大坑 & 秒填方案
| 坑 | 现象 | 急救 |
|---|---|---|
| 非 HTTPS | 调用直接被浏览器拦截 | 上证书,或退到 IP 定位 |
| 用户拒绝授权 | 错误码 1 | 弹窗提示“手动选城市”,别卡死流程 |
| 超时 | 错误码 3 | 把 timeout 设长或降 enableHighAccuracy |
| 坐标偏移 | 国内地图“钉不准” | 用地图商提供的“坐标转换”接口(GCJ-02) |
7. 性能 & 隐私提示
- 只在用户触发时调
getCurrentPosition,避免页面一进来就弹窗。 - 拿到坐标立刻脱敏(截断小数点后 3 位 ≈ 百米级)再发给后端,减少隐私风险。
- 用完即走,别把
watchPosition挂一整天,手机电量肉眼可见地下掉。
8. 一句话总结
“先判 support,再 getCurrentPosition;成功拿 lat/lon,失败换 IP 兜底;HTTPS 是门票,用户授权是钥匙。”
背完这句,下次产品说“我们要定位”——直接甩代码,十分钟收工。
0
快来点个赞吧
发表评论
评论列表