如何使用HTML5地理位置經緯度API?


HTML5地理位置API允許您與您喜歡的網站共享您的位置。JavaScript可以捕獲您的緯度和經度,並可以傳送到後端網路伺服器,並且可以執行高階位置感知操作,例如查詢當地商家或在地圖上顯示您的位置。

地理位置API可以使用全域性navigator物件的新屬性,即地理位置物件。

示例

您可以嘗試執行以下程式碼,以使用地理位置API查詢當前位置,其中包括緯度和經度座標

線上演示

<!DOCTYPE HTML>
<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>
   <body>
      <form>
         <input type="button" onclick="getLocation();" value="Get Location"/>
      </form>
   </body>
</html>

更新於:18-May-2020

628次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始學習
廣告