HTML5 地理定位

HTML5 地理定位(Geolocation)让网页能够获取用户设备的位置信息(经纬度、海拔、速度等)。学习它,你就可以做出"附近店铺""打车定位""天气自动定位"这类位置相关的应用,它不需要任何地图库也能读取原始坐标。

浏览器支持与安全前提

几乎所有现代浏览器都支持 navigator.geolocation 对象。出于隐私考虑,浏览器必须经过用户授权才会返回位置,而且通常要求页面运行在 HTTPS 环境下(http://localhost 除外)。

if ("geolocation" in navigator) {
    console.log("浏览器支持地理定位");
} else {
    console.log("浏览器不支持,请升级");
}

获取当前位置:getCurrentPosition

navigator.geolocation.getCurrentPosition(success, error, options) 只取一次位置。成功回调收到 position 对象,坐标放在 position.coords 里。

<button onclick="getLoc()">获取我的位置</button>
<p id="out"></p>
<script>
function getLoc() {
    navigator.geolocation.getCurrentPosition(showPos);
}
function showPos(pos) {
    var lat = pos.coords.latitude;      // 纬度
    var lng = pos.coords.longitude;     // 经度
    document.getElementById("out").innerHTML =
        "纬度:" + lat + "<br>经度:" + lng;
}
</script>

在浏览器中显示为:点击按钮并允许授权后,页面出现"纬度:xx.xxxx 经度:xx.xxxx"。

持续跟踪位置:watchPosition

watchPosition 会在设备位置变化时反复回调,常用于导航;不再需要时用 clearWatch(id) 停止,id 是 watchPosition 的返回值。

var id = navigator.geolocation.watchPosition(showPos);
// 需要停止跟踪时:
// navigator.geolocation.clearWatch(id);

coords 常用属性

属性含义
coords.latitude纬度(北纬为正)
coords.longitude经度(东经为正)
coords.accuracy精度(米),越小越准
coords.altitude海拔(米)
coords.speed移动速度(米/秒)
coords.heading行进方向(度)
timestamp获取位置的时间戳

错误处理

第二个回调参数用于处理失败,错误对象有一个 code 属性:1 用户拒绝授权、2 位置不可用、3 请求超时。

function showError(err) {
    switch (err.code) {
        case err.PERMISSION_DENIED:
            alert("用户拒绝了位置请求"); break;
        case err.POSITION_UNAVAILABLE:
            alert("位置信息不可用"); break;
        case err.TIMEOUT:
            alert("请求位置超时"); break;
    }
}

选项与易错点

第三个参数可传 { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 },分别表示要高精度、5 秒超时、不使用缓存。

易错点:① 必须用 HTTPS 且用户授权,否则静默失败;② 返回的可能不是 GPS 精确值而是网络估算值,请结合 accuracy 判断;③ 真机测试比 PC 更准确。

小结:用 getCurrentPosition 取一次位置、watchPosition 持续跟踪,配合 position.coords 即可读取经纬度,记得做好错误提示与 HTTPS 前提。

笔记加载中…