Emile
Emile

Reputation: 3484

Displaying multiple routes with Google Maps JS v3

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 -

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.

Upvotes: 0

Views: 1382

Answers (1)

Phillip Thomas
Phillip Thomas

Reputation: 1469

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); 
} 

Upvotes: 1

Related Questions