HTML DOM 地理位置属性
HTML DOM 地理位置坐标属性用于获取用户设备在地球上的位置和海拔高度。用户必须同意提供坐标后,此属性才能生效。这样做是为了不泄露用户的隐私。此属性可用于追踪各种设备的位置。
属性
以下是位置属性 −
注意 −以下属性为只读 −
| 属性 | 描述 |
|---|---|
| position.coords | 返回一个坐标对象,其中包含设备在地球上的纬度、经度、海拔和速度等信息。它还包含一个精度值,描述测量值的精度(以米为单位)。 |
| position.timestamp | 表示位置对象的创建时间和日期。它返回一个表示该时间的 DOMTimeStamp。 |
语法
以下是 Geolocation 位置属性 − 的语法
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 按钮 −

在上面的例子中 −
我们首先创建了一个按钮 COORDINATES,当用户点击该按钮时,它将执行 getCoords() 方法 −
<button onclick="getCoords()">COORDINATES</button>
getCoords() 函数获取导航器对象的 geolocation 属性,以检查浏览器是否支持地理定位。如果浏览器支持地理定位,它将返回一个 Geolocation 对象。使用导航器 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;
}
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

