PHP前端开发

HTML DOM Geolocation coordinates属性

百变鹏仔 4周前 (09-22) #HTML
文章标签 属性

html dom 地理定位坐标属性用于获取用户设备在地球上的位置和海拔高度。用户必须批准他想要提供坐标,此属性才能工作。这样做是为了不损害用户的隐私。这可用于跟踪各种设备的位置。

属性

以下是坐标属性 -

注意 - 所有这些属性是只读的,并且返回类型为 double。

Sr.No th>属性及描述
1 coordinates.latitude

返回设备位置的纬度(以十进制度为单位)。

2坐标.经度

返回设备位置的经度(以十进制度为单位)

3coefficients.altitude

立即学习“前端免费学习笔记(深入)”;

返回位置的海拔高度(以米为单位),相对到海平面。如果设备中没有 GPS,则可以返回 null。

4坐标。精度

返回纬度和经度属性的精度(以米为单位)

5coordinates.altitudeAccuracy返回海拔属性的精度(以米为单位)
6cocos.heading

返回设备行进的方向。该值(以度为单位)表示设备与正北航向的距离。 0度代表真北,方向按顺时针方向确定(东为90度,西为270度)。如果速度为 0,则航向为 NaN。如果设备无法提供航向信息,则该值为 null

7坐标.speed返回设备的速度(以米每秒为单位)。该值可以为 null。

语法

以下是 GeoLocation 坐标属性的语法 -

coordinates.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&#39;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() 函数获取导航器对象的地理定位属性,以检查浏览器是否支持地理定位。如果浏览器支持地理定位,它将返回一个 Geolocation 对象。使用导航器地理定位属性的 getCurrentPosition() 方法,我们可以获得设备的当前位置。 getCurrentPosition() 方法是一个回调函数,它接受一个函数作为其参数的对象,因为每个函数都是 JavaScript 中的一个对象。

这里,我们将 showCoords() 方法传递给它。 showCoords() 方法以位置接口作为参数,并使用它来显示 id 为“Sample”的段落内的经度、纬度和精度。它使用段落innerHTML属性向其附加文本 -

function getCoords() {   if (navigator.geolocation) {      navigator.geolocation.getCurrentPosition(showCoords);   } else {      p.innerHTML ="This browser doesn&#39;t support geolocation.";   }}function showCoords(position) {   p.innerHTML = "Longitude:" + position.coords.longitude + "<br>Latitude: " + position.coords.latitude+"<br>Accuracy: "+ position.coords.accuracy;}