HTML DOM 地理位置 position 屬性
HTML DOM 地理位置 coordinates 屬性用於獲取使用者裝置在地球上的位置和高度。使用者必須批准他們想要提供座標,然後此屬性才能工作。這樣做是為了保護使用者的隱私。這可以用於跟蹤各種裝置的位置。
屬性
以下是 position 屬性:
注意 - 下列屬性為只讀:
| 屬性 | 描述 |
|---|---|
| position.coords | 返回一個座標物件,其中包含諸如緯度、經度、高度和裝置在地球上的速度等資訊。它還具有一個精度值,以米為單位描述測量的準確度。 |
| position.timestamp | 表示建立 position 物件的時間和日期。它返回一個表示該時間的 DOMTimeStamp。 |
語法
以下是 Geolocation position 屬性的語法:
position.property
這裡,屬性可以是上表中的兩個屬性之一。
示例
讓我們來看一個 Geolocation position 屬性的示例:
<!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 按鈕後:

在上面的示例中:
我們首先建立了一個名為 COORDINATES 的按鈕,當用戶點選它時,它將執行 getCoords() 方法:
<button onclick="getCoords()">COORDINATES</button>
getCoords() 函式獲取 navigator 物件的 geolocation 屬性以檢查瀏覽器是否支援地理位置。如果瀏覽器支援地理位置,它將返回一個 Geolocation 物件。使用 navigator geolocation 屬性的 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;
}
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP