Display multiple routes on google map

I am trying to display multiple routes on the same map, but cannot do this.

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 would be helpful.

+6
source share
2 answers

I had the same problem. This thread in the Google Maps group of Google Maps shows how to do this.

The author (a Google employee) wrote the following:

You must create two DirectionsRenderer objects, each of which 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 and it works.

+14
source

Have you tried the following?
Here I captured one path and displayed it. You can do the same by writing pointsArray = result.routes[1].overview_path; besides him and displaying it in a new cycle.

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

Source: https://habr.com/ru/post/907089/


All Articles