Safari 5 中的 HTML5 Geolocation


HTML5 地理位置 API 允許你與你喜愛的網站分享你的位置資訊。JavaScript 可以捕獲你的緯度和經度資訊,並將其傳送至後端 Web 伺服器,用於執行諸如查詢本地商家或在地圖中顯示你的位置等位置相關操作。

示例

讓我們看看如何獲取當前位置:

<!DOCTYPE HTML>
<html>
   <head>
      <script>
         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>

更新於:2020 年 6 月 25 日

904 次瀏覽

開啟你的 職業生涯

透過完成教程獲得認證

開始
廣告