HTML5 词条目录
前端Wiki/HTML5/进阶/拖拽与文件

地理定位 geolocation

geolocation API 让网页获取用户经纬度,入口是 navigator.geolocation。三个要点先记住:必须 HTTPS(localhost 除外);必须用户授权——浏览器会弹询问框,用户拒绝就拿不到;调用是异步的,结果通过回调返回。

两个方法:getCurrentPosition(成功回调, 失败回调, 配置) 取一次位置;watchPosition(同参数) 持续监听位置变化(导航类应用用),返回一个 id,用 clearWatch(id) 停止。成功回调里 pos.coords 包含 latitude(纬度)、longitude(经度)、accuracy(精度,米)。

失败回调的 err.code 有三种:1 权限被拒、2 位置不可用、3 超时。配置项 enableHighAccuracy 请求高精度(更耗电更慢)、timeout 设超时毫秒数、maximumAge 允许缓存多久内的旧位置。拿到坐标后通常交给地图库(如高德、Leaflet)显示。

本节要点geolocation 三前提:HTTPS、用户授权、异步回调;取一次用 getCurrentPosition,持续监听用 watchPosition;务必写失败回调处理"拒绝/超时"。
HTML
<button id="loc">获取我的位置</button>
<p id="tip">等待操作……</p>
<script>
  document.getElementById('loc').addEventListener('click', function () {
    if (!('geolocation' in navigator)) {           // 先做特性检测
      document.getElementById('tip').textContent = '当前浏览器不支持定位';
      return;
    }
    navigator.geolocation.getCurrentPosition(function (pos) {
      var c = pos.coords;
      document.getElementById('tip').textContent =
        '纬度 ' + c.latitude + ',经度 ' + c.longitude +
        ',误差约 ' + c.accuracy + ' 米';
    }, function (err) {
      // 1=用户拒绝  2=位置不可用  3=超时
      document.getElementById('tip').textContent = '定位失败:' + err.message;
    }, {
      enableHighAccuracy: true,   // 高精度(更耗电)
      timeout: 5000,              // 5 秒内没结果就报错
      maximumAge: 0               // 不使用缓存位置
    });
  });
</script>