HTML5 Geolocation API地理定位整理(一)

HTML5 Geolocation API 用于获得用户的地理位置。

鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。

浏览器支持

Internet Explorer 9+, Firefox, Chrome, Safari 和 Opera 支持Geolocation(地理定位).

注意:

1. Geolocation(地理定位)对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确。点击查看更多参考

2.在微信的WebView中可以获取位置,QQ的WebView中 Geolocation不可用。

3.在移动终端的watchPosition()监听触发间隔比PC端短很多。

一、Geolocation对象使用navigator.geolocation访问,

只有3个方法,没有属性

1.getCurrentPosition(successCB,[errorCB],[geolocationOptions]) 方法获取用户的位置

2.watchPosition(successCB,[errorCB],[geolocationOptions]) 方法返回用户的位置并循环监听,时间间隔不一定

3.clearWatch() ---清楚watchPosition()的监听实例

特别说明:

successCB中参数为Geoposition对象

errorCB中参数为PositionError对象

geolocationOptions 参数对象说明:

1.enableHighAccuracy:指示获取位置的精确度,默认为false。如果设置为true,使用精确定位(卫星定位/GPS),在PC端浏览器基本上都执行errorCB,也就是获取失败

2.timeout:获取位置的最长等待时间,默认不限时间

3.maximumAge:接受不超过指定时间毫秒的缓存位置,也就是在重复获取位置时,多长时间之后再次获取位置。

注:在Google浏览器测试修改时间参数并没有效果,待确认。

二、Geoposition对象

获取位置成功返回的对象

1.coords 坐标信息

2.timestamp 获取位置的时间戳

始终会返回 latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。

属性描述
coords.latitude 十进制数的纬度
coords.longitude 十进制数的经度
coords.accuracy 位置精度
coords.altitude 海拔,海平面以上以米计
coords.altitudeAccuracy 位置的海拔精度
coords.heading 方向,从正北开始以度计
coords.speed 速度,以米/每秒计
timestamp 响应的日期/时间

三、PositionError对象

获取位置信息失败时返回的对象

  • Permission denied - 用户不允许地理定位
  • Position unavailable - 无法获取当前位置
  • Timeout - 操作超时

 四、使用实例

1.判断浏览器是否支持Geolocation对象

if (navigator.geolocation) {
    console.info(navigator.geolocation);
} else {
    console.log('你的浏览器不支持地理定位');
}

2.获取用户位置

if (navigator.geolocation) {
    //获取地理位置需要等比较长的一段时间
    //尤其是在PC段,根据IP获取的
    navigator.geolocation.getCurrentPosition(successCB, errorCB);
} else {
    console.log('你的浏览器不支持地理定位');
}
//获取地理位置成功
function successCB(position) {
    console.info(position);
    console.log('位置精度:'+position.coords.accuracy);
    console.log('维度:'+position.coords.latitude);
    console.log('经度:'+position.coords.longitude);
}
//获取地理位置失败
function errorCB(error) {
    console.error(error);
    var msg='';
    switch (error.code) {
        case error.PERMISSION_DENIED:
            msg = "用户拒绝对获取地理位置的请求。"
            break;
        case error.POSITION_UNAVAILABLE:
            msg = "位置信息是不可用的。"
            break;
        case error.TIMEOUT:
            msg = "请求用户地理位置超时。"
            break;
        case error.UNKNOWN_ERROR:
            msg = "未知错误。"
            break;
    }
    console.error(msg);
}

3.使用精确模式

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(locationSuccess, locationError,{
        // 指示浏览器获取高精度的位置,默认为false
        enableHighAccuracy: true,
        // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
        timeout: 5000,
        // 最长有效期,在重复获取地理位置时,此参数指定多久再次获取位置。
        maximumAge: 3000
    });
}else{
    alert("Your browser does not support Geolocation!");
}

 

 

更多:

HTML5 Geolocation API地理定位整理(二)

HTML5 离线缓存详解(转)

HTML5 History对象,Javascript修改地址栏而不刷新页面(二)

HTML5 Geolocation API工作原理[转载]

posted @ 2017-02-28 13:32  天马3798  阅读(7577)  评论(0编辑  收藏  举报