从google Direction API获取包含原点和航点但没有目的地的路线

时间:2018-01-25 12:56:52

标签: google-maps shortest-path

我想使用只有原点和航点的Google Direction API来获取没有目标点的最短路径。这可能吗?

1 个答案:

答案 0 :(得分:0)

我担心你不能,目的地是所有Directions API请求中的必需参数,但你可以在没有路标的情况下进行请求。

如果你想要最短的路径,你只需要遍历响应即可获得它。

以下是如何执行此操作的示例:https://jsbin.com/nihihis/1/edit?html,js,output

在此我迭代响应,并将最短路径显示为绿色,最长路径显示为红色。

 var request = {
        origin: start,
        destination: end,
        travelMode: "DRIVING",
        provideRouteAlternatives: true
    };
    directionsService.route(request, function(response, status) {
        console.log('init');
        console.log('status ' + status);
        if (status == 'OK') {

            console.log('results', response.routes);
            //
            var routesSteps = [];
            var routes = response.routes;
            var colors = ['red', 'black', 'green'];

            for (var i = 0; i < routes.length; i++) {

              if(i==0) {
                new google.maps.DirectionsRenderer({
                    map: map,
                    directions: response,
                    routeIndex: i,
                    polylineOptions: {

                        strokeColor: colors[2],
                        strokeWeight: 4,
                        strokeOpacity: .3
                    }
                });
              } else if(i== routes.length - 1) {
                new google.maps.DirectionsRenderer({
                    map: map,
                    directions: response,
                    routeIndex: i,
                    polylineOptions: {

                        strokeColor: colors[0],
                        strokeWeight: 4,
                        strokeOpacity: .3
                    }
                });
              } else {
                new google.maps.DirectionsRenderer({
                    map: map,
                    directions: response,
                    routeIndex: i,
                    polylineOptions: {

                        strokeColor: colors[1],
                        strokeWeight: 4,
                        strokeOpacity: .3
                    }
                });
              }