代码示例:(标识:js_api_geolocation_watchposition)
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Geolocation API</h1>

<p>单击按钮以获取您的坐标。</p>

<button onclick="getLocation()">试一试</button>

<p id="demo"></p>

<script>
const x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.watchPosition(showPosition);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}
    
function showPosition(position) {
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
}
</script>

</body>
</html>
运行结果: