gpt4 book ai didi

javascript - 如何使用 google map api 获得精确位置?

转载 作者:行者123 更新时间:2023-11-28 04:32:50 24 4
gpt4 key购买 nike

我正在尝试在 map 上显示用户的当前位置。使用 HTML5 地理位置,它会询问用户许可,我觉得这很烦人,我发现我可以通过直接使用 google map api 来绕过这个问题。

问题在于,无论采用哪种解决方案,精度都可能会偏低(偏离 300 公里)。

HTML5 解决方案

https://developers.google.com/maps/documentation/javascript/geolocation

这是google提供的例子,效果很好。此外,不同浏览器的准确性也会发生变化。

Google map API 解决方案

这是我已经达到的代码。

function calculateZoomLevel(accuracy) {
var equatorLength = 40075004; // in meters
var mapWidth = 480; // in pixels
var metersPerPixel = equatorLength / 4096;
var zoomLevel = 1;
while ((metersPerPixel * mapWidth) > accuracy) {
metersPerPixel /= 2;
zoomLevel++;
}
return Math.min(zoomLevel, 17);
}
function initMap() {
var coords = new google.maps.LatLng(37.990832, 23.70332), accuracy = 0;
$.post('https://www.googleapis.com/geolocation/v1/geolocate?key=MY_API_KEY').done(function(e) {
coords = new google.maps.LatLng(e.location.lat, e.location.lng);
accuracy = e.accuracy;
map = new google.maps.Map(document.getElementById('map'), {
zoom: calculateZoomLevel(accuracy),
center: coords,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
new google.maps.Circle({
center: coords,
radius: accuracy,
map: map,
fillColor: '#ff0000',
fillOpacity: .5,
strokeColor: '#ff0000',
strokeOpacity: .5
});
}).fail(function(e) {
console.log('fail ajax post geolocation', e);
});
}

问题是,我知道精度可能相当好(10-30 米),因为在同一时间和同一个浏览器上,我看到自己在 google 的示例中完全偏离了某个地方,我看到自己处于我所在的位置正常的谷歌地图页面。

最佳答案

因此,如果您不想以大量请求为代价来捕获和计算最可能的位置,或者您不想制作自己的脚本来连接到此 api,这将是一个挑战...创建循环阈值。如果函数的精度不合理,请记忆一下您的函数。含义:

   coords = new google.maps.LatLng(e.location.lat, e.location.lng);
accuracy = e.accuracy;
var c = 0;
if (c<20){
If (accuracy <100){
.. do your stuff..
}else{
initMap();
c++;
}
}else{
...failed....
}

所以对明智的人来说...这会以明显的方式增加你的要求。你已经被警告过......除非当你读到这篇文章时谷歌允许无限制的免费请求。

关于javascript - 如何使用 google map api 获得精确位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479377/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com