HTML5地理定位-Geolocation API

HTML5提供了一组Geolocation API,来自navigator定位对象的子对象,获取用户的地理位置信息
Geolocation API使用方法:
1.判断是否支持 navigator.geolocation
2.调用getCurrentPosition(successCallback, errorCallback, options),返回定位数据
参数说明:
参数1:successCallback 成功的回调函数,把position对象作为参数传入,position对象包含定位的相关信息


  latitude           纬度数值
  longitude          经度数值
  speed              运动的速度(假设你在地平线上运动),单位米/秒。
  accuracy           精确度单位米
  altitude           高度,单位米
  altitudeAccuracy   高度的精确地,单位米
  heading            运动的方向,相对于正北方向的角度。
 

参数2:errorCallback 出错的回调函数


  error.PERMISSION_DENIED:  用户拒绝对获取地理位置的请求。
  error.POSITION_UNAVAILABLE:  位置信息是不可用的。
  error.TIMEOUT:  请求用户地理位置超时。
  error.UNKNOWN_ERROR:  未知错误。
  

参数3:options 选项配置


  enableHighAccuracy: true   指示浏览器获取高精度的位置
  timeout: 5000              指定获取地理位置的超时时间,默认不限时,单位为毫秒
  maximumAge: 3000           最长有效期,即位置缓存

代码示例:


<script type="text/javascript">
//支持html5的浏览器才可以使用Geolocation API
//console.log(navigator.geolocation);
if(navigator.geolocation){
    //console.log("支持!");
    //参数1:
    function successFn(position) {
        //latitude  纬度
        //longitude 经度
        console.log("position",position);
        console.log(position.coords);
        console.log("纬度 ",position.coords.latitude,"经度 ",position.coords.longitude);
    }

    //参数2:
    function errorFn(error) {
        switch(error.code) {
            case error.PERMISSION_DENIED:
                console.log("用户拒绝对获取地理位置的请求User denied the request for Geolocation.");
                break;
            case error.POSITION_UNAVAILABLE:
                console.log("位置信息是不可用Location information is unavailable.");
                break;
            case error.TIMEOUT:
                console.log("用户的请求超时The request to get user location timed out.");
                break;
            case error.UNKNOWN_ERROR:
                console.log("未知错误An unknown error occurred.");
                break;
        }
    }

    //参数3:
    var options = {
        // 指示浏览器获取高精度的位置
        enableHighAccuracy: true,
        // 指定获取地理位置的超时时间,默认不限时,单位为毫秒
        timeout: 5000,
        // 最长有效期,即位置缓存
        maximumAge: 3000
    }

    //返回定位数据,如果出错返回错误信息,链接超时的配置
    navigator.geolocation.getCurrentPosition(successFn,errorFn,options);
}
else{
    console.log("不支持! Geolocation is not supported by this browser.");
}
</script>

注意:google浏览器在国内无法直接定位

原文地址:https://segmentfault.com/a/1190000014939935

猜你喜欢

转载自www.cnblogs.com/lalalagq/p/9911131.html