如何在 JavaScript 中獲取使用者位置的經緯度?


可以使用 getCurrentPosition() 方法找到使用者當前的位置。HTML5 提供的地理位置 API 允許我們知道使用者的地理位置。地理位置 API 提供使用者當前位置的經緯度,然後透過 JavaScript 傳遞到後端並在網站上顯示。

GeolocationCoordinates 介面的只讀 longitude 屬性是一個雙精度浮點值,表示位置的經度,以十進位制度表示。

GeolocationCoordinates 物件是 GeolocationPosition 介面的一部分,因為它是 Geolocation API 呼叫傳遞的物件型別,這些呼叫收集並傳遞地理位置,以及提供測量時間的 DOMTimeStamp。

語法

navigator.geolocation.getCurrentPosition(success, error, options);

引數 - 它包含三個引數,如下所示,並在上面詳細說明

  • success - 當 getCurrentPosition() API 方法的資料成功收集時,使用此函式。

  • error - 它還包含一個回撥函式,用於傳送位置的警告和錯誤。

  • options - 設定計時器、啟用高精度和最大年齡很有幫助。

以十進位制度表示的 longitude 值表示 Coordinates 物件描述的地球上的精確位置。1984 年的世界大地測量系統定義指定了該值 (WGS 84)。

示例 1

以下示例使用使用者的地理位置來演示 Geolocation getCurrentPosition() 方法。

<!DOCTYPE html> <html> <title>Latitude and longitude of the user's position in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body style="text-align:center"> <h1 style="color: rgba(14, 21, 126, 0.908)">Welcome To Tutorialspoint!</h1> <h3>Click the button to identify the users location</h3> <div> <button onclick="myGeolocator()"> Get location </button> <div id="result"></div> </div> <script> let result = document.getElementById("result"); let userLocation = navigator.geolocation; function myGeolocator() { if(userLocation) { userLocation.getCurrentPosition(success); } else { "The geolocation API is not supported by your browser."; } } function success(data) { let lat = data.coords.latitude; let long = data.coords.longitude; result.innerHTML = "Latitude: " + lat + "<br>Longitude: " + long; } </script> </body> </html>

示例 2

在這個例子中,讓我們瞭解如何獲取精度和時間戳。

<!DOCTYPE html> <html> <title>Latitude and longitude of the user's position in JavaScript - TutorialsPoint</title> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body style="text-align:center"> <h1 style="color: rgba(14, 21, 126, 0.908)">Welcome To Tutorialspoint!</h1> <h3>Click the button to get accuracy and timestamp of the users location</h3> <div> <button onclick="myGeolocator()"> Get accuracy and timestamp </button> <div id="result"></div> </div> <script> let result = document.getElementById("result"); let userLocation = navigator.geolocation; function myGeolocator() { if (userLocation) { userLocation.getCurrentPosition(success); } else { "The geolocation API is not supported by your browser"; } } function success(data) { let accur = data.coords.accuracy; let timstamp = data.timestamp; result.innerHTML = "Accuracy: " + accur + "<br>Time Stamp: " + timstamp; } </script> </body> </html>

更新於: 2022年8月23日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.