HTML5地理定位-Geolocation API

HTML5提供了一組Geolocation API,來自navigator定位對象的子對象,獲取用戶的地理位置信息
Geolocation API使用方法:
1.判斷是否支持 navigator.geolocation
2.調用getCurrentPosition(successCallback, errorCallback, options),返回定位數據
參數說明:
參數1:successCallback 成功的回調函數,把position對象做爲參數傳入,position對象包含定位的相關信息javascript

latitude           緯度數值
  longitude          經度數值
  speed              運動的速度(假設你在地平線上運動),單位米/秒。
  accuracy           精確度單位米
  altitude           高度,單位米
  altitudeAccuracy   高度的精確地,單位米
  heading            運動的方向,相對於正北方向的角度。

參數2:errorCallback 出錯的回調函數html

error.PERMISSION_DENIED:  用戶拒絕對獲取地理位置的請求。
  error.POSITION_UNAVAILABLE:  位置信息是不可用的。
  error.TIMEOUT:  請求用戶地理位置超時。
  error.UNKNOWN_ERROR:  未知錯誤。

參數3:options 選項配置html5

enableHighAccuracy: true   指示瀏覽器獲取高精度的位置
  timeout: 5000              指定獲取地理位置的超時時間,默認不限時,單位爲毫秒
  maximumAge: 3000           最長有效期,即位置緩存

代碼示例:java

<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瀏覽器在國內沒法直接定位git

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

相關文章
相關標籤/搜索