html5中的GPS定位功能

weixin_34391445發表於2017-06-01

html5中的GPS定位功能主要用的是getCurrentPosition,該方法封裝在 navigator.geolocation 屬性裡,是 navigator.geolocation 物件的方法。

getCurrentPosition()函式簡介

getCurrentPosition(successCallback,errorCallback,positionOptions)
successCallback

表示呼叫getCurrentPosition函式成功以後的回撥函式,該函式帶有一個引數,物件字面量格式,表示獲取到的使用者位置資料。該物件包含兩個屬性 coords 和 timestamp。其中 coords 屬性包含以下7個值:

accuracy:精確度
latitude:緯度
longitude:經度
altitude:海拔
altitudeAcuracy:海拔高度的精確度
heading:朝向
speed:速度
errorCallback

和 successCallback 函式一樣帶有一個引數,物件字面量格式,表示返回的錯誤程式碼。它包含以下兩個屬性:

1、message:錯誤資訊
2、 code:錯誤程式碼。

其中錯誤程式碼包括以下四個值:

1、UNKNOW_ERROR:表示不包括在其它錯誤程式碼中的錯誤,這裡可以在 message 中查詢錯誤資訊
2、PERMISSION_DENIED:表示使用者拒絕瀏覽器獲取位置資訊的請求
3、 POSITION_UNAVALIABLE:表示網路不可用或者連線不到衛星
4、TIMEOUT:表示獲取超時。必須在options中指定了timeout值時才有可能發生這種錯誤
positionOptions

positionOptions 的資料格式為JSON,有三個可選的屬性:

1、enableHighAcuracy — 布林值: 表示是否啟用高精確度模式,如果啟用這種模式,瀏覽器在獲取位置資訊時可能需要耗費更多的時間。
2、timeout — 整數: 表示瀏覽需要在指定的時間內獲取位置資訊,否則觸發errorCallback。
3、maximumAge — 整數/常量: 表示瀏覽器重新獲取位置資訊的時間間隔。
getCurrentPosition()函式定位應用

<!DOCTYPE HTML>
   <head>
      <script type="text/javascript">

         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            alert("Latitude : " + latitude + " Longitude: " + longitude);
         }

         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }

         function getLocation(){

            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);
            }else{
               alert("Sorry, browser does not support geolocation!");
            }
         }

      </script>

   </head>

   <html>
      <body>
         <form>
            <input type="button" onclick="getLocation();" value="Get Location"/>
         </form>
      </body>
   </html>

點選按鈕,就可以回提示是否獲取當前位置,允許之後,可以獲取你所在位置的經緯度!

相關文章