HTML5中的Geolocation定位

Author: 刘老师(Aaron Lau) 武汉长乐教育,武汉PHP培训课程,版权所有,转载请注明!

HTML5中的Geolocation定位

本课摘要

  1. getCurrentPosition 获取定位方法
  2. watchPosition 位置发生变化, 就重新获取
  3. updateLocation 成功获取到位置的回调
  4. handleLocationError 获取定位失败的回调

1. getCurrentPosition 获取定位方法

//10秒超时
navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError, {timeout: 10000});
  1. 第一个参数为 updateLocation, 成功获取定位的回调.
  2. 第二个参数为 handleLocationError, 获取定位失败的回调.
  3. 第三个参数为可选{},为Json对象, 是设置部分请求的特性.

其中第三个可选参数,又有以下几个可选

  1. enableHighAccuracy: 是否高度精确模式, 默认为false, 注意开启此模式, 资源和时间开销更多, 而且可能结果没有差别.

  2. timeout, 多少秒超时

  3. maxmumAge, 重新计算定位的间隔,设置为0, 每次都重新获取, 设置为Infinity,则仅在第一次获取.

2. watchPosition 位置发生变化, 就重新获取, 更新数据

//监控位置是否发生变化
var watchId = navigator.geolocation.watchPosition(updateLocation, handleLocationError);

//停止获取定位
navigator.geolocation.clearWatch(watchId);

3. updateLocation 成功获取到位置的回调

function updateLocation(position) {
    console.log(position.coords.latitude);       //纬度
    console.log(position.coords.longitude);      //经度
    console.log(position.coords.accuracy);       //精确度, 单位m

    console.log(position.coords.altitude);      //海拔高度, 单位m
    console.log(position.coords.altitudeAccuracy); //海拔高度准确度, 单位m

    console.log(position.coords.heading);      //行进方向, 相对于正北
    console.log(position.coords.speed);      //速度, 单位m/s
}

4. handleLocationError 获取定位失败的回调

function handleLocationError(error) {
    switch(error.code)
    {
    case 0:
      console.log("未知错误" + error.message);
      break;
    case 1:
      console.log("用户拒绝使用定位");
      break;
    case 2:
      console.log("获取失败" + error.message);
      break;
    case 3:
      console.log("获取超时");
      break;
    }
}
上一篇课程 下一篇课程

学生登录