首页 > 解决方案 > Google Maps Javascript API - places.AutocompleteService - getPlacePredictions 在满足某些条件时返回错误的距离米

问题描述

谷歌地图 Javascript API 版本 3.44.5

我调用 getPlacePredictions 从某些用户输入、“原点”偏向和“地址”类型中获取预测。预测 distance_meters 在某些情况下是错误的:当输入不对应于现有的街道号码,但足够接近以便引擎能够估计位置时。距离错误证明:取返回的place_id,使用Geocoder获取geometry.location,最后计算坐标之间的距离。在此示例中,我们得到 547 与 2481 米。

另外,请考虑 Villate 250 返回547米(错误),与Villate 280 的距离相同,与Villate 350相同......但 Villate 456 返回 2390 米(正确)......然后再次 Villate 480 返回547米(错误)等等……

漏洞 ?我误解了什么吗?谢谢

const OriginLat = -34.52211;
const OriginLon = -58.499669;
const exampleInput = "villate 250";

var service = new google.maps.places.AutocompleteService();
var geocoder = new google.maps.Geocoder();

service.getPlacePredictions({  input: exampleInput
                                                   , type: ["address"]
                                                   , componentRestrictions: { country: 'ar' }
                                                   , origin: new google.maps.LatLng( OriginLat, OriginLon )
                                                   , radius: 1
}, displaySuggestions);

const displaySuggestions = function(predictions, status) {
               
    // Values
    console.log(predictions[0].place_id);
    // EkBDYXJsb3MgVmlsbGF0ZSAyNTAsIE9saXZvcywgUHJvdmluY2lhIGRlIEJ1ZW5vcyBBaXJlcywgQXJnZW50aW5hIlESTwo0CjIJc8WRg0SxvJURdeB0wGKPz_caHgsQ7sHuoQEaFAoSCb-oQzIdsbyVEYvJh6S0OZzZDBD6ASoUChIJz6lHjCixvJURF-aUHiYnCg4

    console.log(predictions[0].distance_meters);
    // 547m
};

geocoder.geocode({placeId: place_id}, geocoderResult);

const geocoderResult = function(results, status) {

  let resultPos = results[0].geometry.location;
  console.log(resultPos);
  // -34.51032,-58.476673

  // Distance Recalc
  distance_meters = fncLocalDistance(resultPos.lat(), resultPos.lng(), OriginLat, OriginLon);
  // 2481m
};

// Distance between coords
function fncLocalDistance(lat1, lon1, lat2, lon2) {
        if ((lat1 == lat2) && (lon1 == lon2)) {return 0}

        let radlat1 = Math.PI * lat1/180;
        let radlat2 = Math.PI * lat2/180;
        let theta = lon1-lon2;
        let radtheta = Math.PI * theta/180;
        let dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
        if (dist > 1) {dist = 1}
        dist = Math.acos(dist);
        dist = dist * 180/Math.PI;
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344 * 1000;
       
        return dist;
}

标签: google-maps-api-3

解决方案


推荐阅读