Compute the distance between polyline (route) and

2019-04-09 10:26发布

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条回答
孤傲高冷的网名
2楼-- · 2019-04-09 11:14

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.

查看更多
登录 后发表回答