Google地图api v3:使用DistanceMatrixService查找多个路径

Google map api v3: find multiple paths using DistanceMatrixService

本文关键字:查找 路径 DistanceMatrixService 使用 地图 api v3 Google      更新时间:2023-09-26

我使用谷歌地图api在DistanceMatrixService()的帮助下寻找两点之间的距离。在getdistancemmatrix()的成功回调中,我可以得到两点之间的距离。两点之间可能有多条路径但我总能求出最短路径的长度。我怎样才能得到所有的路径距离呢?请参考以下代码:

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix({
    origins: [--some origins--],
    destinations: [--some destinations--],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    avoidHighways: false,
    avoidTolls: false,
}, function (response, status) {
        for (var i = 0, length = response.rows[0].elements.length; i < length; i++) {
            if (response.rows[0].elements[i].status == 'NOT_FOUND') {
                alert('Source or destination address could not be found.');
                return;
            }
            var distance = response.rows[0].elements[i].distance.text;
            var duration = response.rows[0].elements[i].duration.text;
        }
});

在上面的代码中,数组response.rows[0].elements的长度总是为1。如果源和目标之间有多条路径,则应该有多个对象。如何做到这一点?

distancemmatrix不允许多条路由,它总是计算最短/最佳距离。

如果你需要替代路由,只有一个来源和目的地,用户DirectionsService,设置provideRouteAlternativestrue

从文档:

provideRouteAlternatives (optional)设置为true时,指定Directions服务可以在响应中提供多个路由选择。请注意,提供替代路由可能会增加服务器的响应时间。