JavaScript - 地理位置 API



地理位置 API

地理位置 API 是一個 Web API,它提供了一個 JavaScript 介面來訪問使用者的地理位置資料。地理位置 API 包含您可以用來在您的網站上訪問使用者位置的各種方法和屬性。

它使用裝置的 GPS 檢測使用者的位置。位置的準確性取決於 GPS 裝置的準確性。

由於位置會影響使用者的隱私,因此它會在訪問位置之前請求許可權。如果使用者授予許可權,網站可以訪問緯度、經度等。

有時,開發人員需要在網站上獲取使用者的位置。例如,如果您正在建立 Ola、Uber 等型別的應用程式,您需要了解使用者的位置才能接他們乘坐。

地理位置 API 允許使用者與特定網站共享位置。

地理位置 API 的即時用例

以下是地理位置 API 的即時用例。

  • 獲取使用者的位置座標,並在地圖上顯示它們。

  • 在照片上標記使用者的位置。

  • 向用戶推薦附近的商店、美食廣場、加油站等。

  • 獲取產品或食品配送的當前位置。

  • 從使用者當前位置接載使用者。

使用地理位置 API

要使用地理位置 API,您可以使用視窗物件的“navigator”屬性。Navigator 物件包含“geolocation”屬性,其中包含用於操作使用者位置的各種屬性和方法。

語法

請按照以下語法使用地理位置 API。

var geolocation = window.navigator.geolocation;
OR
var geolocation = navigator.geolocation;

在這裡,geolocation 物件允許您訪問位置座標。

示例:檢查瀏覽器支援

使用 navigator,您可以檢查使用者的瀏覽器是否支援 Geolocation.geolocation 屬性。

以下程式碼根據 Geolocation 是否受支援列印相應的訊息。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上列印它。

<html>
<body>
  <div id = "output"> </div>
  <script>
    const output = document.getElementById("output");
    if (navigator.geolocation) {
      output.innerHTML += "Geolocation is supported by your browser."
    } else {
      output.innerHTML += "Geolocation is not supported by your browser."
    }
  </script>
  </body>
</html>

輸出

Geolocation is supported by your browser.

地理位置方法

以下是地理位置 API 的方法。

方法 描述
getCurrentPosition() 它用於檢索網站使用者的當前地理位置。
watchPosition() 它用於持續更新使用者的即時位置。
clearWatch() 使用 watchPosition() 方法清除使用者位置的正在進行的監控。

位置屬性

getCurrentPosition() 方法執行您作為引數傳遞的回撥函式。回撥函式將物件作為引數。引數物件包含有關使用者位置的資訊的各種屬性。

在這裡,我們在下面的表格中列出了位置物件的所有屬性。

屬性 型別 描述
coords 物件 它是您作為 getCurrentPosition() 方法的回撥函式引數獲得的物件。它包含以下屬性。
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 物件的時間的資訊。

獲取使用者的位置

您可以使用 getCurrentPosition() 方法獲取使用者當前的位置。

語法

使用者可以按照以下語法使用 getCurrentPosition() 方法獲取使用者當前的位置。

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options);

引數

getCurrentPosition() 物件接受 3 個引數。

  • successCallback − 當方法成功獲取使用者位置時,將呼叫此函式。

  • errorCallback − 當方法在訪問使用者位置時發生錯誤時,將呼叫此函式。

  • Options − 這是一個可選引數。它是一個包含超時、maxAge 等屬性的物件。

允許網站訪問您的位置

每當任何網站嘗試訪問您的位置時,瀏覽器都會彈出許可權警報框。如果您點選“允許”,則可以獲取您的位置詳細資訊。否則,它會丟擲一個錯誤。

您可以在下圖中看到許可權彈出視窗。

示例

在下面的程式碼中,我們使用 getCurrentPosition() 方法獲取使用者的位置。該方法呼叫 getCords() 函式來獲取當前位置。

在 getCords() 函式中,我們列印 cords 物件各個屬性的值。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上列印它。

<html>
<body>
  <h3> Location Information </h3>
  <button onclick = "findLocation()"> Find Location </button>
  <p id = "output"> </p> 
  <script>
    const output = document.getElementById("output");
    function findLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(getCords); //
      }
      else {
        output.innerHTML += "Geo Location is not supported by this browser!";
      }
    }
    // Callback function
    function getCords(coords) {
      output.innerHTML += "The current position is: <br>";
      output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
      output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
      output.innerHTML += "Accuracy: " + coords.coords.accuracy + "<br>";
      output.innerHTML += "Altitude: " + coords.coords.altitude + "<br>";
    }  
  </script>
</body>
</html>

地理位置錯誤

getCurrentPosition() 方法將回調函式作為第二個引數來處理錯誤。回撥函式可以將錯誤物件作為引數。

在以下情況下,可能會發生錯誤。

  • 當用戶拒絕訪問位置時。

  • 當位置資訊不可用時。

  • 當位置請求超時時。

  • 它也可能產生任何隨機錯誤。

以下是錯誤物件的屬性列表。

屬性 型別 描述
code 數字 它包含錯誤程式碼。
message 字串 它包含錯誤訊息。

以下是不同錯誤程式碼的列表。

程式碼 常量 描述
0 UNKNOWN_ERROR 當 geolocation 物件的方法無法檢索位置時,它會返回程式碼 0 表示未知錯誤。
1 PERMISSION_DENIED 當用戶拒絕訪問位置的許可權時。
2 POSITION_UNAVAILABLE 當它無法找到裝置的位置時。
3 TIMEOUT 當 geolocation 物件的方法無法找到使用者的位置時。

示例:錯誤處理

我們在下面的程式碼中的 findLocation() 函式中使用 getCurrentPosition() 方法。我們將 errorCallback() 函式作為 getCurrentPosition() 方法的第二個引數傳遞,以處理錯誤。

在 errorCallback() 函式中,我們使用 switch case 語句根據錯誤程式碼列印不同的錯誤訊息。

當您點選“查詢位置”按鈕時,它會顯示一個彈出視窗,詢問您是否允許訪問位置。如果您點選“阻止”,它會顯示一個錯誤。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上列印它。

<html>
<body>
<div id = "output"> </div>
<button onclick = "findLocation()"> Find Location </button>
<script>
const output = document.getElementById("output");
function findLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(getCords, errorCallback); //
  }
  else {
    output.innerHTML += "Geo Location is not supported by this browser!";
  }
}
// Callback function
function getCords(coords) {
  output.innerHTML += "The current position is: <br>";
  output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
  output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
}
// Function to handle error
function errorCallback(err) {
  switch (err.code) {
    case err.PERMISSION_DENIED:
      output.innerHTML += "You have denied to access your device's location";
      break;
    case err.POSITION_UNAVAILABLE:
      output.innerHTML += "Your position is not available.";
      break;
    case err.TIMEOUT:
      output.innerHTML += "Request timed out while fetching your location.";
      break;
    case err.UNKNOWN_ERROR:
      output.innerHTML += "Unknown error occurred while fetching your location.";
      break;
  }
}  
</script>
</body>
</html>

地理位置選項

getCurrentPosition() 方法將包含選項的物件作為第三個引數。

以下是您可以作為鍵傳遞給選項物件的選項列表。

屬性 型別 描述
enableHighAccuracy 布林值 它表示您是否希望獲取最準確的位置。
timeout 數字 它接受毫秒數作為值,表示您希望等待獲取位置資料的時間。
maximumAge 數字 它接受毫秒數作為值,指定快取位置的最大年齡。

示例

下面的程式碼查詢最準確的位置。此外,我們還將毫秒設定為選項物件的 maximumAge 和 timeout 屬性。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上列印它。

<html>
<body>
<div id = "output"> </div>
<button onclick = "findLocation()"> Find Location </button>
<script>
  const output = document.getElementById("output");
  function findLocation() {
    if (navigator.geolocation) {
      // Options for geolocation
      const options = {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      };
      navigator.geolocation.getCurrentPosition(getCords, errorfunc, options);
    }
    else {
      output.innerHTML += "Geo Location is not supported by this browser!";
    }
  }
  // Callback function
  function getCords(coords) {
    output.innerHTML += "The current position is: <br>";
    output.innerHTML += "Latitude: " + coords.coords.latitude + "<br>";
    output.innerHTML += "Longitude: " + coords.coords.longitude + "<br>";
  }
  function errorfunc(err) {
    output.innerHTML += "The error message is - " + err.message + "<br>";
  }
</script>
</body>
</html>

監視使用者的當前位置

watchPosition() 方法允許您跟蹤使用者的即時位置。它返回 ID,當您要停止跟蹤使用者時,可以將其與 clearWatch() 方法一起使用。

語法

請按照以下語法使用 watchPosition() 方法來跟蹤使用者的即時位置。

var id = navigator.geolocation.watchPosition(successCallback, errorCallback, options)  

errorCallback 和 options 是可選引數。

如果要停止跟蹤使用者,可以按照以下語法操作。

navigator.geolocation.clearWatch(id);  

clearWatch() 方法將 watchPosition() 方法返回的 id 作為引數。

示例

在下面的程式碼中,我們使用 geolocation 物件的 watchPosition() 方法來獲取使用者的連續位置。

我們將 getCords() 函式作為 watchPosition() 方法的回撥函式,在其中列印使用者位置的緯度和經度。

在 findLocation() 方法中,我們使用 setTimeOut() 方法在 30 秒後停止跟蹤。

在輸出中,您可以觀察到程式碼多次列印使用者的位置。

首先,我們將資料轉換為 JSON 格式。之後,我們將資料轉換為字串並在網頁上列印它。

<html>
<body>
  <button onclick = "findLocation()"> Find Location </button>
  <div id = "output"> </div>
  <script>
    let output = document.getElementById("output");
    function findLocation() {
      if (navigator.geolocation) {
        let id = navigator.geolocation.watchPosition(getCoords);
        setTimeout(function () {
          navigator.geolocation.clearWatch(id);
          output.innerHTML += "<br>Tracking stopped!";
        }, 30000); // Stop tracking after 30 seconds.
      } else {
        output.innerHTML += "<br>Geo Location is not supported by this browser!";
      }
    }
    // Callback function
    function getCoords(location) {
      let latitude = location.coords.latitude;
      let longitude = location.coords.longitude;
      output.innerHTML += `<br> Latitude: ${latitude}, Longitude: ${longitude}`;
    }
  </script>
</body>
</html>
廣告