HTML - 地理位置 API



HTML 地理位置 API 用於 Web 應用程式訪問使用者的地理位置。大多數現代瀏覽器和移動裝置都支援 地理位置 API

JavaScript 可以捕獲您的緯度和經度,並可以傳送到後端 Web 伺服器,並執行諸如查詢本地企業或在地圖上顯示您的位置等複雜的基於位置的功能。

語法

var geolocation = navigator.geolocation;

地理位置物件是一個服務物件,允許小部件檢索有關裝置地理位置的資訊。

地理位置 API 方法

地理位置 API 提供以下方法

方法 描述
getCurrentPosition()

此方法檢索使用者的當前地理位置。

watchPosition()

此方法檢索有關裝置當前地理位置的定期更新。

clearWatch()

此方法取消正在進行的 watchPosition 呼叫。

示例

以下是使用上述任何方法的示例程式碼

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showLocation, errorHandler);

   watchId = geolocation.watchPosition(showLocation, errorHandler, {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
  });

  navigator.geolocation.clearWatch(watchId);
}

這裡,showLocationerrorHandler 是回撥方法,將用於獲取實際位置(如下一節所述)以及處理可能出現的錯誤。

位置屬性

地理位置方法 getCurrentPosition()getPositionUsingMethodName() 指定檢索位置資訊的回撥方法。這些方法與儲存完整位置資訊的 Position 物件非同步呼叫。

Position 物件指定裝置的當前地理位置。位置表示為一組地理座標以及有關航向和速度的資訊。

下表描述了 Position 物件的屬性。對於可選屬性,如果系統無法提供值,則該屬性的值設定為 null。

屬性 型別 描述
coords 物件 指定裝置的地理位置。位置表示為一組地理座標以及有關航向和速度的資訊。
coords.latitude 數字 指定以十進位制度表示的緯度估計值。值範圍為 [-90.00,+90.00]。
coords.longitude 數字 指定以十進位制度表示的經度估計值。值範圍為 [-180.00,+180.00]。
coords.altitude 數字 [可選] 指定相對於 WGS 84 參考橢球面的海拔高度估計值(以米為單位)。
coords.accuracy 數字 [可選] 指定緯度和經度估計值的精度(以米為單位)。
coords.altitudeAccuracy 數字 [可選] 指定海拔高度估計值的精度(以米為單位)。
coords.heading 數字 [可選] 指定裝置當前運動方向(以度為單位),相對於正北方向順時針方向計算。
coords.speed 數字 [可選] 指定裝置當前地面速度(以米/秒為單位)。
timestamp 日期 指定檢索位置資訊和建立 Position 物件的時間。

示例

以下是使用“position”物件的示例程式碼。這裡,showLocation() 方法是一個回撥方法

function showLocation( position ) {
  var latitude = position.coords.latitude;
  var longitude = position.coords.longitude;
  ...
}

處理錯誤

地理位置很複雜,非常需要捕獲任何錯誤並優雅地處理它。

地理位置方法 getCurrentPosition()watchPosition() 使用錯誤處理回撥方法,該方法提供 PositionError 物件。此物件具有以下兩個屬性

屬性 型別 描述
code 數字 包含錯誤的數字程式碼。
message 字串 包含錯誤的人類可讀描述。

下表描述了 PositionError 物件中返回的可能錯誤程式碼。

程式碼 常量 描述
0 UNKNOWN_ERROR 由於未知錯誤,該方法無法檢索裝置的位置。
1 PERMISSION_DENIED 該方法無法檢索裝置的位置,因為應用程式沒有許可權使用位置服務。
2 POSITION_UNAVAILABLE 無法確定裝置的位置。
3 TIMEOUT 該方法無法在指定的最大超時間隔內檢索位置資訊。

示例

以下是使用 PositionError 物件的示例程式碼。這裡 errorHandler 方法是一個回撥方法

function errorHandler( err ) {
   if (err.code == 1) {
      // access is denied
   }
   ...
}

位置選項

以下是 getCurrentPosition() 方法的實際語法

getCurrentPosition(callback, ErrorCallback, options)

這裡,第三個引數是 PositionOptions 物件,它指定了一組用於檢索裝置地理位置的選項。

以下是可以作為第三個引數指定的選項

屬性 型別 描述
enableHighAccuracy 布林值 指定小部件是否希望接收儘可能準確的位置估計。預設情況下,此值為 false。
timeout 數字 timeout 屬性是 Web 應用程式願意等待位置的毫秒數。
maximumAge 數字 指定快取位置資訊的過期時間(以毫秒為單位)。

示例

以下是顯示如何使用上述方法的示例程式碼

function getLocation() {
   var geolocation = navigator.geolocation;
   geolocation.getCurrentPosition(showLocation, 
                                  errorHandler, 
                                  {maximumAge: 75000});
}

HTML 地理位置 API 示例

以下是一些示例,展示瞭如何在 HTML 中訪問地理位置

獲取當前位置

以下程式碼顯示瞭如何使用 JavaScript 和 HTML 訪問裝置的當前位置。

<!DOCTYPE html>
<html>
<head>
      <title>
         Geolocation API Example
      </title>
</head>
<body>

   <h2>Geolocation API Example</h2>
   <p id="demo">
      Click the button to get your coordinates:
   </p>
   <button onclick="getLocation()">
      Show Location
   </button>

   <script>
      var x = document.getElementById("demo");

      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
         } else {
            x.innerHTML = 
            "Geolocation is not supported by this browser.";
         }
      }

      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude + 
         "<br>Longitude: " + position.coords.longitude;
      }
         
   </script>

</body>
</html>

地理位置中的錯誤處理

以下是顯示如何使用上述方法的示例程式碼

<!DOCTYPE html>
<html>
<head>
      <title>Geolocation API Example</title>
</head>

<body>
   <h2>Geolocation API Example</h2>
   <p id="demo">
      Turn off location service of your device, 
      See how the error is handled.
   </p>
   <button onclick="getLocation()">
      Show Location
   </button>

   <script>
      var x = document.getElementById("demo");

      function getLocation() {
         if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
         } else {
            x.innerHTML = "Geolocation is not supported by this browser.";
         }
      }

      function showPosition(position) {
         x.innerHTML = "Latitude: " + position.coords.latitude + 
         "<br>Longitude: " + position.coords.longitude;
      }

      function showError(error) {
         switch(error.code) {
            case error.PERMISSION_DENIED:
                  x.innerHTML = 
                  "User denied the request for Geolocation.";
                  break;
            case error.POSITION_UNAVAILABLE:
                  x.innerHTML = 
                  "Location information is unavailable.";
                  break;
            case error.TIMEOUT:
                  x.innerHTML = 
                  "The request to get user location timed out.";
                  break;
            case error.UNKNOWN_ERROR:
                  x.innerHTML = 
                  "An unknown error occurred.";
                  break;
         }
      }
   </script>

</body>
</html>

支援的瀏覽器

API Chrome Edge Firefox Safari Opera
地理位置 9.0 3.5 5.0 16.0
廣告