【问题标题】:How can I get precise location with google maps api?如何使用谷歌地图 api 获得精确位置?
【发布时间】: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。无论哪种方式,谷歌地图官方页面都不会要求权限,并且非常准确。

标签: javascript google-maps


【解决方案1】:

因此,如果您不想以大量请求为代价来捕获和计算最可能的位置,或者您不想制作自己的脚本来连接到此 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....
}

所以告诉智者...这将以明显的方式增加您的要求。您已被警告.....除非谷歌在您阅读本文时允许无限制的免费请求。

【讨论】:

    猜你喜欢
    • 2020-11-28
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 2017-06-08
    • 1970-01-01
    • 2018-03-08
    相关资源
    最近更新 更多