Compute the distance between polyline (route) and marker in Google Maps API v3

守給你的承諾、 提交于 2019-12-21 17:44:49

问题


Is there any convenient way to compute the direct (shortest) distance between Polyline (the route generated by Google Directions) and markers that are NOT situated on that polyline?

The only way I found out is to cycle through Polyline.getPath() vertices manually to calculate the shortest distance but it seems to be a bit harsh:

var path = routes[0].overview_path;

for (var i = 0; i < data.points.length; i++) {
    var latLngA = new LatLng(data.points[i].lat, data.points[i].lng);
    var shortest_distance = null;

    for (var j = 0; j < path.length; j++) {
        var distance = google.maps.geometry.spherical.computeDistanceBetween(latLngA, path[i]);

        if (shortest_distance == null || distance < shortest_distance) {
            shortest_distance = distance;
        }
    }

    console.log(data.points[i].point_title, shortest_distance);
}

Thanks in advance!


回答1:


As far as I know, the Google Maps API does not give you a way to do this easily. And unfortunately, the algorithm you use will not give an accurate answer, because it gives the distance from the marker to the closest vertex on the path, not the closest point on the polyline itself, which will usually not be one of the points.

If you really need an accurate calculation, the best option I know of is to use the Javascript Topology Suite (JSTS). JSTS has a ton of geographic formulas for calculating this sort of thing. That means converting the polyline returned from the directions API into a JSTS object and calling the right utility function. Not trivial, but not too difficult either.



来源:https://stackoverflow.com/questions/13750122/compute-the-distance-between-polyline-route-and-marker-in-google-maps-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!