You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中获取近似经纬度并保留4位小数,隐藏截图中圈出的提示

解决方案

修改说明

  • 保留4位小数:通过toFixed(4)方法对获取到的经纬度做四舍五入格式化,符合精度要求
  • 隐藏提示:如果是要隐藏页面上的坐标展示文本,直接给对应DOM元素加display: none样式即可;如果是要隐藏浏览器的定位授权弹窗,仅用原生Geolocation API无法实现,可改用IP定位方案获取近似坐标,无需用户授权不会触发弹窗

完整可运行代码

<!DOCTYPE html>
<html>
<body>
  <p>点击按钮获取你的坐标</p>
  <button onclick="getLocation()">点击获取</button>
  <!-- 不需要展示坐标文本可保留display:none隐藏,需要展示的话删除该样式即可 -->
  <p id="demo" style="display: none;"></p>
  <input type="text" id="lat" name="lat" placeholder="纬度">
  <input type="text" id="lon" name="lon" placeholder="经度">

  <script>
    const demoEle = document.getElementById("demo");
    const latInput = document.getElementById("lat");
    const lonInput = document.getElementById("lon");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
      } else {
        demoEle.innerText = "当前浏览器不支持定位功能";
      }
    }

    function showPosition(position) {
      // 四舍五入保留4位小数
      const formattedLat = position.coords.latitude.toFixed(4);
      const formattedLon = position.coords.longitude.toFixed(4);
      demoEle.innerHTML = `纬度:${formattedLat}<br>经度:${formattedLon}`;
      latInput.value = formattedLat;
      lonInput.value = formattedLon;
    }

    // 定位错误处理逻辑
    function showError(error) {
      switch(error.code) {
        case error.PERMISSION_DENIED:
          demoEle.innerText = "用户拒绝了定位请求";
          break;
        case error.POSITION_UNAVAILABLE:
          demoEle.innerText = "位置信息不可用";
          break;
        case error.TIMEOUT:
          demoEle.innerText = "请求定位超时";
          break;
        case error.UNKNOWN_ERROR:
          demoEle.innerText = "定位发生未知错误";
          break;
      }
    }
  </script>
</body>
</html>

内容的提问来源于stack exchange,提问作者NANG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:24:03