Google Maps Directions API - 按下按钮

时间:2016-08-26 11:32:33

标签: javascript google-maps-api-3 google-maps-direction-api

如何在按钮点击时更改Google地图上当前显示的路线?目前,我只能显示正在返回的主要路由。我也可以循环遍历API返回的所有路由。我似乎无法找到改变我所拥有的路线之间的显示方式。以下是我到目前为止的情况。

<!DOCTYPE html>
<html>
<head>
    <title>Google Maps API Implementation</title>
    <script src="http://maps.googleapis.com/maps/api/js"></script>
    <script>
        var directionsDisplay = new google.maps.DirectionsRenderer();
        var directionsService = new google.maps.DirectionsService();
        var validRoutes = [];

        function initialize() {

            // ----- MAP SETUP ----- //
            var pierLocation = new google.maps.LatLng(14.6023936,120.9591289);
            var destinationLat = 14.60540879665969; // Sample data only
            var destinationLong = 120.9795238; // Sample data only
            var destinationLocation = new google.maps.LatLng(destinationLat,destinationLong);

            var mapProperties = {
                center:pierLocation,
                zoom:15,
                mapTypeId:google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("googleMap"),mapProperties);

            directionsDisplay.setMap(map);
            calculateRoutes(pierLocation, destinationLocation);

        }

        function calculateRoutes(pierLocation, destinationLocation) {
            var request = {
                origin: pierLocation,
                destination: destinationLocation,
                travelMode: 'DRIVING',
                provideRouteAlternatives: true
            };
            directionsService.route(request, function(result, status) {
                if (status === 'OK') {
                    directionsDisplay.setDirections(result);
                    var summaryPanel = document.getElementById('directions-panel');
                    summaryPanel.innerHTML = '';

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

                        new google.maps.DirectionsRenderer({
                            map: googleMap,
                            directions: result,
                            routeIndex: x
                        });

                        summaryPanel.innerHTML += '<hr><br><b> Route ' + (x+1) + ':<br>';
                        var route = result.routes[x];
                        for (var y=0; y<route.legs.length; y++) {
                            var routeSegment = y + 1;

                            summaryPanel.innerHTML += route.legs[y].start_address + ' to ';
                            summaryPanel.innerHTML += route.legs[y].end_address + '<br>';
                            summaryPanel.innerHTML += route.legs[y].distance.text + '<br><br>';

                            var steps = route.legs[y].steps;
                            for (var z=0; z<steps.length; z++) {
                                var nextSegment = steps[z].path;
                                summaryPanel.innerHTML += "<li>" + steps[z].instructions;

                                var dist_dur = "";
                                if (steps[z].distance && steps[z].distance.text) dist_dur += steps[z].distance.text;
                                if (steps[z].duration && steps[z].duration.text) dist_dur += "&nbsp;"+steps[z].duration.text;
                                if (dist_dur != "") {
                                summaryPanel.innerHTML += "("+dist_dur+")<br /></li>";
                                } else {
                                summaryPanel.innerHTML += "</li>";
                                }

                            }

                            summaryPanel.innerHTML += "<br>";
                        }
                    }
                }
                 else {
                    window.alert('Directions request failed due to ' + status);
                    }
            });
        }

        google.maps.event.addDomListener(window, 'load', initialize);

    </script>
</head>
<body>
    <div id="googleMap" style="width:500px;height:380px;"></div><br>
    <label id="directions-panel"></label>
</body>
</html>

Here is a screenshot

提前致谢!!

1 个答案:

答案 0 :(得分:0)

使用DirectionsDisplay.setRouteIndex()

<input id="btn1" type="button" value="route1" onclick="directionsDisplay.setRouteIndex(0);" />
<input id="btn2" type="button" value="route2" onclick="directionsDisplay.setRouteIndex(1);" />
<input id="btn3" type="button" value="route3" onclick="directionsDisplay.setRouteIndex(2);" />

proof of concept fiddle

代码段

var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var validRoutes = [];
var map;

function initialize() {

  // ----- MAP SETUP ----- //
  var pierLocation = new google.maps.LatLng(14.6023936, 120.9591289);
  var destinationLat = 14.60540879665969; // Sample data only
  var destinationLong = 120.9795238; // Sample data only
  var destinationLocation = new google.maps.LatLng(destinationLat, destinationLong);

  var mapProperties = {
    center: pierLocation,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById("googleMap"), mapProperties);

  directionsDisplay.setMap(map);
  calculateRoutes(pierLocation, destinationLocation);

}

function calculateRoutes(pierLocation, destinationLocation) {
  var request = {
    origin: pierLocation,
    destination: destinationLocation,
    travelMode: 'DRIVING',
    provideRouteAlternatives: true
  };
  directionsService.route(request, function(result, status) {
    if (status === 'OK') {
      directionsDisplay.setDirections(result);
      var summaryPanel = document.getElementById('directions-panel');
      summaryPanel.innerHTML = '';

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

        new google.maps.DirectionsRenderer({
          map: map,
          directions: result,
          routeIndex: x
        });

        summaryPanel.innerHTML += '<hr><br><b> Route ' + (x + 1) + ':<br>';
        var route = result.routes[x];
        for (var y = 0; y < route.legs.length; y++) {
          var routeSegment = y + 1;

          summaryPanel.innerHTML += route.legs[y].start_address + ' to ';
          summaryPanel.innerHTML += route.legs[y].end_address + '<br>';
          summaryPanel.innerHTML += route.legs[y].distance.text + '<br><br>';

          var steps = route.legs[y].steps;
          for (var z = 0; z < steps.length; z++) {
            var nextSegment = steps[z].path;
            summaryPanel.innerHTML += "<li>" + steps[z].instructions;

            var dist_dur = "";
            if (steps[z].distance && steps[z].distance.text) dist_dur += steps[z].distance.text;
            if (steps[z].duration && steps[z].duration.text) dist_dur += "&nbsp;" + steps[z].duration.text;
            if (dist_dur != "") {
              summaryPanel.innerHTML += "(" + dist_dur + ")<br /></li>";
            } else {
              summaryPanel.innerHTML += "</li>";
            }

          }

          summaryPanel.innerHTML += "<br>";
        }
      }
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
  
html,
body,
#googleMap {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="googleMap" style="width:500px;height:380px;"></div><br>
<input id="btn1" type="button" value="route1" onclick="directionsDisplay.setRouteIndex(0);" />
<input id="btn2" type="button" value="route2" onclick="directionsDisplay.setRouteIndex(1);" />
<input id="btn3" type="button" value="route3" onclick="directionsDisplay.setRouteIndex(2);" />
    <label id="directions-panel"></label>