當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


HTML Geolocation position用法及代碼示例


HTML DOM中的Geolocation position屬性用於返回設備在地球上的位置。返回的Coordinates對象可以用於各種目的,包括導航和跟蹤設備的位置。

返回值:

  • position.coords:具有當前位置的所有信息的坐標對象。
  • position.timestamp:它表示DOMTimeStamp,它表示獲取位置的時間。

用法:getCurrentPosition()或watchPosition()之類的方法用於將回調傳遞給函數,然後訪問position屬性。


例:

<!DOCTYPE html> 
<html> 
  
<title> 
    DOM Geolocation position Property 
</title> 
  
<body> 
    <h1 style = "color:green"> 
        GeeksforGeeks 
    </h1> 
      
    <b> 
        DOM Geolocation position Property 
    </b> 
      
    <p> 
        Click the button to get your position. 
    </p> 
      
    <button onclick = "getLocation()"> 
        Get Location 
    </button> 
      
    <p class = "location"></p> 
  
    <script> 
        let x = document.querySelector('.location'); 
      
        function getLocation() { 
      
            /* Check if location support is available */ 
            if (navigator.geolocation) { 
      
                /* Callback to the showPosition function */ 
                navigator.geolocation.getCurrentPosition(showPosition); 
            } else {  
                x.innerHTML = "Geolocation is not supported."; 
            } 
        } 
      
        function showPosition(position) { 
            x.innerHTML = "Latitude:" +  
              
            /* Get the latitude from the Coordinates object */ 
            position.coords.latitude +  
      
            "<br>Longitude:" +  
      
            /* Get the longitude from the Coordinates object */ 
            position.coords.longitude + 
              
            "<br>Timestamp:" + 
              
            /* Get the timestamp of the location obtained */ 
            position.timestamp; 
        } 
    </script> 
</body> 
  
</html>                    

輸出:
之前單擊按鈕:
before-button
單擊按鈕後:
after-button

支持的瀏覽器:下麵列出了DOM Geolocation position屬性支持的瀏覽器:

  • 穀歌瀏覽器5.0
  • Internet Explorer 9.0
  • Firefox 3.5
  • Opera 16.0
  • Safari 5.0


相關用法


注:本文由純淨天空篩選整理自sayantanm19大神的英文原創作品 HTML | DOM Geolocation position Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。