Displaying multiple routes with Google Maps JS v3

时间:2018-02-26 17:45:15

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

I am trying to load a dynamic number of routes onto a single map. Of the solutions I've found on SO, they all seem to hard code the number of points instead of dynamically processing them.

My Solution

In this example, I'm handling multiple shipments and then trying to plot the route on the Google Maps with DirectionsService. This means -

  • Looping over each shipment
  • Grabbing the startPoint & endPoint
  • Making the request
  • Processing the response

Code

The solution I've come up with is -

function initMap(shipments) {
  var shipments = shipments;
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom:4
  });
  var infowindow = new google.maps.InfoWindow();
  var bounds = new google.maps.LatLngBounds();

  // Plot Points
  if (shipments.length > 0) {
      for (i = 0; i < shipments.length; i++) {
          var startPoint = {};
          var endPoint = {};
          // Each Shipment
          for (z = 0; z < shipments[i]['points'].length; z++) {
            var point  = shipments[i]['points'][z]
            var lat = point['point'][0]
            var lng = point['point'][1]
            var marker = new google.maps.Marker({
              position: new google.maps.LatLng(lat, lng),
              map: map,
              label: point['name'],
              icon: 'http://maps.google.com/mapfiles/ms/icons/'+ point['color'] +'.png',
            });
            bounds.extend(marker.position);
            if (marker.label == 'start') {
              startPoint = {lat: lat, lng: lng};
            }
            if (marker.label == 'destination') {
              endPoint = {lat: lat, lng: lng};
            }
          }
          var request = {
            origin: startPoint,
            destination: endPoint,
            travelMode: 'DRIVING'
          };
          var directionsService = new google.maps.DirectionsService();
          var directionsDisplay = new google.maps.DirectionsRenderer({
            map: map,
            suppressMarkers: true
          });
          directionsDisplay.setMap(map);
          directionsService.route(request, function(response, status) {
            if (status == 'OK') {
              // Display the route on the map.
              directionsDisplay.setDirections(response);
            }
          });
          // map.fitBounds(bounds);
      };
  }
}

Problem

The problem is that this only plots the last shipment instead of plotting and rendering each. Where am I not processing the response properly? The data is going through correctly, but it is rendering the following -

enter image description here

Thank you in advance for your help.

1 个答案:

答案 0 :(得分:1)

You are really close! You will need to create a google.maps.DirectionsRenderer per route. Keep in mind you will also need to keep track of these renders for removal, clean up, etc. Try something like this:

function initMap(shipments) {
  var shipments = shipments;
  var map = new google.maps.Map(document.getElementById('map'), {
      zoom:4
  });
  var directionsService = new google.maps.DirectionsService();
  var infowindow = new google.maps.InfoWindow();
  var bounds = new google.maps.LatLngBounds();

  // Plot Points
  if (shipments.length > 0) {
      for (i = 0; i < shipments.length; i++) {
          var startPoint = {};
          var endPoint = {};
          // Each Shipment
          for (z = 0; z < shipments[i]['points'].length; z++) {
            var point  = shipments[i]['points'][z]
            var lat = point['point'][0]
            var lng = point['point'][1]
            var marker = new google.maps.Marker({
              position: new google.maps.LatLng(lat, lng),
              map: map,
              label: point['name'],
              icon: 'http://maps.google.com/mapfiles/ms/icons/'+ point['color'] +'.png',
            });
            bounds.extend(marker.position);
            if (marker.label == 'start') {
              startPoint = {lat: lat, lng: lng};
            }
            if (marker.label == 'destination') {
              endPoint = {lat: lat, lng: lng};
            }
          }
          var request = {
            origin: startPoint,
            destination: endPoint,
            travelMode: 'DRIVING'
          };

          directionsService.route(request, function(response, status) {
            if (status == 'OK') {
              // Display the route on the map.
              console.log(response)
              renderDirections(response, map);
            }
          });
          // map.fitBounds(bounds);
      };
  }
}

function renderDirections(result, map) { 
    var directionsRenderer = new google.maps.DirectionsRenderer({
    map: map,
    suppressMarkers: true
  }); 
  directionsRenderer.setMap(map); 
    directionsRenderer.setDirections(result); 
}