HTML DOM Geolocation 坐標屬性用於獲取用戶在地球上的設備位置和高度。在此屬性起作用之前,用戶必須批準他/她想要提供坐標。這樣做是為了不損害用戶隱私。這可用於跟蹤各種設備位置。
特性
以下是位置屬性 -
注意− 以下屬性是隻讀的 −
屬性 | 描述 |
---|---|
position.coords | 返回一個坐標對象,其中包含設備在地球上的緯度、經度、高度和速度等信息。它還具有一個準確度值,用於描述以米為單位的測量準確度。 |
position.timestamp | 表示創建位置對象的時間和日期。它返回一個代表那個時間的 DOMTimeStamp。 |
用法
以下是地理位置位置屬性的語法 -
position.property
這裏,屬性可以是上表中的兩個屬性之一。
示例
讓我們看一個 Geolocation 位置屬性的例子 -
<!DOCTYPE html>
<html>
<body>
<h1>Geolocation coordinates property</h1>
<p>Get you coordinates by clicking the below button</p>
<button onclick="getCoords()">COORDINATES</button>
<p id="Sample">Your coordinates are:</p>
<script>
var p = document.getElementById("Sample");
function getCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showCoords);
} else {
p.innerHTML ="This browser doesn't support geolocation.";
}
}
function showCoords(position) {
p.innerHTML = "Longitude:" + position.coords.longitude +
"<br>Latitude:" + position.coords.latitude+"
<br>Accuracy:"+ position.coords.accuracy;
}
</script>
</body>
</html>
輸出
這將產生以下輸出 -
單擊坐標按鈕 -
在上麵的例子中 -
我們首先創建了一個按鈕 COORDINATES,當用戶單擊時,它將執行 getCoords() 方法 -
<button onclick="getCoords()">COORDINATES</button>
getCoords() 函數獲取導航器對象地理定位屬性來檢查瀏覽器是否支持地理定位。如果瀏覽器支持地理定位,它將返回一個地理定位對象。使用導航器地理定位屬性的 getCurrentPosition() 方法,我們可以獲得設備的當前位置。 getCurrentPosition() 方法是一個回調函數,它將一個函數作為其參數的對象,因為在 JavaScript 中每個函數都是一個對象。
在這裏,我們將 showCoords() 方法傳遞給它。 showCoords() 方法以位置接口為參數,用它來顯示id 為“Sample” 的段落內的經度、緯度和精度。它使用段落 innerHTML 屬性向其附加文本 -
function getCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showCoords);
} else {
p.innerHTML ="This browser doesn't support geolocation.";
}
}
function showCoords(position) {
p.innerHTML = "Longitude:" + position.coords.longitude +
"<br>Latitude:" + position.coords.latitude+"<br>Accuracy:"+ position.coords.accuracy;
}
相關用法
- HTML DOM Geolocation coordinates屬性用法及代碼示例
- HTML DOM Style overflowY屬性用法及代碼示例
- HTML DOM Document hidden屬性用法及代碼示例
- HTML DOM IFrame用法及代碼示例
- HTML DOM Textarea cols屬性用法及代碼示例
- HTML DOM Style pageBreakAfter屬性用法及代碼示例
- HTML DOM Base href屬性用法及代碼示例
- HTML DOM Pre用法及代碼示例
- HTML DOM Input Month用法及代碼示例
- HTML DOM Video canPlayType()用法及代碼示例
- HTML DOM Range deleteContents()用法及代碼示例
- HTML DOM console.dirxml()用法及代碼示例
- HTML DOM Style transition屬性用法及代碼示例
- HTML DOM Video volume屬性用法及代碼示例
- HTML DOM Input Range用法及代碼示例
- HTML DOM Style outlineOffset屬性用法及代碼示例
- HTML DOM Storage setItem()用法及代碼示例
- HTML DOM TableHeader用法及代碼示例
- HTML DOM Style maxWidth屬性用法及代碼示例
- HTML DOM NodeIterator whatToShow屬性用法及代碼示例
注:本文由純淨天空篩選整理自AmitDiwan大神的英文原創作品 HTML DOM Geolocation position property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。