【发布时间】:2017-06-11 00:41:10
【问题描述】:
我正在尝试在地图上显示用户的当前位置。使用 HTML5 地理位置,它会询问用户的许可,我觉得这很烦人,我发现我可以通过直接使用 google maps api 绕过这个。
问题在于,无论采用哪种解决方案,准确度都可能会下降(300 公里)。
HTML5解决方案
https://developers.google.com/maps/documentation/javascript/geolocation
这是 google 提供的示例,它很好。精度也会因浏览器而异。
谷歌地图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 米),因为同时在同一个浏览器上,我看到自己在谷歌示例中完全偏离的地方,我看到自己在我的位置普通的谷歌地图页面。
【问题讨论】:
-
浏览器地理位置的准确性由许多因素决定。允许网站使用该信息也取决于用户的判断。非浏览器方法可能使用用户 IP 地址,您已经发现(谢天谢地)不是很准确
-
浏览器没有任何确定位置的方法,它依赖于主机系统。可以通过各种方式提供位置,例如 GPS、手机塔三边测量或 IP 检测。如果您绕过用户的许可,那么它很可能会退回到 IP 检测,对我来说,检测距离可达 1,000 公里。
-
google 示例请求许可并且与使用 google api 的示例具有相同的准确性。很确定那是因为浏览器解决方案也是基于 google api。无论哪种方式,谷歌地图官方页面都不会要求权限,并且非常准确。