AJ.
AJ.

Reputation: 2569

Displaying multiple routes on a google map

I am trying to display multiple routes on same map but am unable to do so.

No matter what I do I get only one route.

function calcRoute() {
        var start = document.getElementById('start').value;
        var end = document.getElementById('end').value;
        var request = {
          origin: start,
          destination: end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(request, function(response, status) {
          if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
          }
        });
      }

Any pointers will be helpful.

Upvotes: 6

Views: 8760

Answers (2)

Joshua Frank
Joshua Frank

Reputation: 13848

I had the same problem. This thread on a Google group for Google maps shows how to do it.

The author (a Google employee), wrote this:

You should be able to create two DirectionsRenderer objects, each that use the same map and different DirectionsResults.

var map = new google.maps.Map(document.getElementById("map_canvas"));
function renderDirections(result) {
  var directionsRenderer = new google.maps.DirectionsRenderer;
  directionsRenderer.setMap(map);
  directionsRenderer.setDirections(result);
}

var directionsService = new google.maps.DirectionsService;
function requestDirections(start, end) {
  directionsService.route({
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  }, function(result) {
    renderDirections(result);
  });
}
requestDirections('Huntsville, AL', 'Boston, MA');
requestDirections('Bakersfield, CA', 'Vancouver, BC');

I tried it and it does work.

Upvotes: 17

Aquarius_Girl
Aquarius_Girl

Reputation: 22946

Did you try as follows?
Here I have captured one path and displayed it. You can do the same by writing pointsArray = result.routes[1].overview_path; besides it and display it in a new loop.

directionsService.route (request, function (result, status) 
        {
            if (status == google.maps.DirectionsStatus.OK)
            {
                directionsDisplay.setDirections (result);
                pointsArray = result.routes[0].overview_path;

                var i = 0;
                var j = 0;

                for (j = 0; j < pointsArray.length; j++)
                {
                    var point1 = new google.maps.Marker ({
                                                    position:pointsArray [j],
                                                    draggable:false,
                                                    map:map,
                                                    flat:true
                                                    });
                }
            }
        });

Upvotes: 0

Related Questions