如何在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
相关产品推荐
相关产品推荐

