地理位置 getCurrentPosition() API



HTML 地理位置 **getCurrentPosition()** 方法檢索裝置的當前地理位置。位置表示為一組地理座標,以及關於航向和速度的資訊。位置資訊以 Position 物件的形式返回。

語法

以下是 HTML 地理位置 **getCurrentPosition()** 方法的語法:

getCurrentPosition(showLocation, ErrorHandler, options);

引數

HTML 地理位置 **getCurrentPosition()** 方法接受以下引數:

  • **showLocation** - 指定檢索位置資訊的回撥方法。此方法以非同步方式呼叫,並使用一個對應於 **Position** 物件的物件,該物件儲存返回的位置資訊。

  • **ErrorHandler** - 此可選引數指定在處理非同步呼叫時發生錯誤時呼叫的回撥方法。此方法使用儲存返回錯誤資訊的 **PositionError** 物件進行呼叫。

  • **options** - 此可選引數指定一組用於檢索位置資訊的選項。您可以指定 (a) 返回的位置資訊的精度 (b) 檢索位置資訊的時間超時,以及 (c) 使用快取的位置資訊。

返回值

getCurrentPosition() 方法不返回值。

示例

讓我們看看 getCurrentPosition() 方法的一個示例:

<!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>

當我們執行以上程式碼時,它將生成一個按鈕,點選該按鈕將提示使用者裝置的位置。

html_geolocation.htm
廣告

© . All rights reserved.