使用Leaflet时调用geoLocation.getCurrentPosition()获取的位置不正确如何解决
问题原因
- Leaflet API传参格式错误:
L.map.setView()的参数结构为([纬度, 经度], 缩放级别),L.marker()仅接收[纬度, 经度]作为坐标参数。你的代码中将缩放值、定位精度值都写入了坐标数组,直接导致坐标计算异常,标记点位置偏离实际位置。 - 未开启高精度定位:
navigator.geolocation.getCurrentPosition()默认使用低精度模式,需手动配置参数开启高精度定位才能获取更准确的位置信息。 - 协议限制:如果页面运行在HTTP协议下,多数现代浏览器会限制定位能力,返回的位置精度会大幅降低,建议部署到HTTPS环境测试。
修复后代码
<!DOCTYPE HTML> <html lang="en"> <head> <title>Open-Source Map with Javascript</title> <link rel="stylesheet" href="leaflet.css"/> <link rel="icon" href="favicon.png"> <meta charset="UTF-8"> <meta name="author" content="Phil"> <script src="leaflet.js"></script> </head> <body> <div style="height: 100vh; width: 100vw; top:0; position: absolute; left: 0; z-index: 10" id="mapid"></div> <div id="div_alert" style=" box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.2); position:absolute; display: none; text-align: center; vertical-align: center; z-index: 100; height: 75px; width: 350px;line-height: 75px; background: white; border-radius: 10px; top: 43%; left: 41%; color: gray;"></div> <script> let div_alert = document.getElementById("div_alert"); // 修正setView传参,缩放级别作为第二个独立参数传入 let mymap = L.map('mapid').setView([52.4315096,7.7865093], 18.12); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png').addTo(mymap); // 修正marker传参,移除坐标数组中的缩放值 L.marker([52.4315096,7.7865093]).addTo(mymap).bindPopup("<b>Location</b><br />Test").openPopup(); mymap.invalidateSize(); function getPosition() { if(navigator.geolocation) // 新增定位配置,开启高精度,设置超时时间和缓存有效期 navigator.geolocation.getCurrentPosition(showPosition, showPositionError, { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 }); } function showPosition(position) { try{ div_alert.innerHTML = "已获取当前位置"; div_alert.style.display = "block"; setTimeout(function() { // 修正setView传参,移除坐标数组中的精度值,单独设置缩放级别 mymap.setView([position.coords.latitude,position.coords.longitude], 18); div_alert.style.display = "none"; // 修正marker传参,移除坐标数组中的精度值 L.marker([position.coords.latitude,position.coords.longitude]) .addTo(mymap).bindPopup("<b>Location</b><br />当前位置").openPopup(); }, 3000); } catch (e){ alert("出现错误:[" + e + "]"); console.log(e); } } // 新增定位失败处理逻辑 function showPositionError(error) { let errMsg = ""; switch(error.code) { case error.PERMISSION_DENIED: errMsg = "用户拒绝了定位请求"; break; case error.POSITION_UNAVAILABLE: errMsg = "位置信息不可用"; break; case error.TIMEOUT: errMsg = "定位请求超时"; break; case error.UNKNOWN_ERROR: errMsg = "未知定位错误"; break; } div_alert.innerHTML = errMsg; div_alert.style.display = "block"; setTimeout(() => { div_alert.style.display = "none"; }, 3000); } getPosition(); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Dev-91823
相关产品推荐
相关产品推荐

