HTML Navigator geolocation 属性

htmlweb developmentfront end technology更新于 2025/12/21 19:56:17

HTML Navigator geolocation 属性返回一个 Geolocation 对象,可用于定位用户的位置。

语法

以下是语法 −

navigator.geolocation

让我们看一个 HTML Navigator geolocation 属性的示例 −

示例

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 20px;
      width: 330px;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show {
      font-size: 1.2rem;
      color: #fff;
   }
</style>
<body>
<h1>HTML navigator geolocation property Demo</h1>
<button class="btn" onclick="display()">Display your position</button>
<div class="show"></div>
<script>
   function display() {
      var userLocation = navigator.geolocation;
      userLocation.getCurrentPosition(displayPosition);
   }  
   function displayPosition(pos) {
      document.querySelector(".show").innerHTML = "<p>Your latitude coordinate is: " +          pos.coords.latitude + "</p>" + "<p>Your longitude coordinate is: " + pos.coords.longitude + "</p>"
   }
</script>
</body>
</html>

输出

点击"显示您的位置"按钮,显示用户的位置坐标 −


相关文章


有用资源