1

I have created multiple routes using Google map api.

I need to change the color and highlight the route while click any of the routes in Google map.

// Added code for multiple Routes.

let directionsService = new google.maps.DirectionsService;
let directionsDisplay;
directionsService.route({
  origin: {
    lat: sourceLat,
    lng: sourceLon
  },
  destination: {
    lat: destLat,
    lng: destLon
  },
  provideRouteAlternatives: true,
  travelMode: google.maps.TravelMode['DRIVING']
}, (res, status) => {
  if (status == google.maps.DirectionsStatus.OK) {
    for (var i = 0, len = res.routes.length; i < len; i++) {
      directionsDisplay = new google.maps.DirectionsRenderer({
        map: this.map,
        directions: res,
        routeIndex: i,
        suppressMarkers: true,
        polylineOptions: {
          strokeColor: "darkgrey",
          strokeOpacity: 1.0,
          strokeWeight: 7
        }
      });
    }
  }
});

// Added event Listener to change the route color. But this is not working and also am not getting any error.

google.maps.event.addListener(directionsDisplay, 'click', function(event) {

  directionsDisplay.setOptions({
    map: this.map,
    directions: res,
    routeIndex: 0,
    polylineOptions: {
      strokeColor: 'green',
      strokeOpacity: 1.0,
      strokeWeight: 7
    }
  });

  directionsDisplay.setMap(this.map);
});

Thanks in Advance.

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
Udhra
  • 17
  • 4
  • What have you tried so far to do that? Don´t see any attemp.. In general it is pretty easy. You need a click event, which have access to the reference of the route. Then you can use the `setOptions{}` method to change the color. – el solo lobo Jan 09 '19 at 15:04
  • google.maps.event.addListener(directionsDisplay, 'click', function (event) { directionsDisplay.setOptions({ polylineOptions: { strokeColor: 'blue', strokeOpacity: 1.0, strokeWeight: 7 } }); directionsDisplay.setMap(this.map); }); This is the code which I have tried. – Udhra Jan 10 '19 at 06:27
  • If you have tried something, then update your question with what you did, what doesn't work, error messages, etc. – MrUpsidown Jan 10 '19 at 09:41
  • I have updated my Question. Please help. – Udhra Jan 10 '19 at 10:18
  • 1
    DirectionsRenderer doesn't have a click event. I'd suggest to trigger the color change when clicking on another element. If you need it when clicking on the polyline, then don't set the renderer on the map. Instead, create your own Polyline from the Directions Route overview path or overview polyline. Polylines can have click events. – MrUpsidown Jan 10 '19 at 15:32
  • 1
    related question: [Google Maps click event on route](https://stackoverflow.com/questions/17902574/google-maps-click-event-on-route) – geocodezip Jan 10 '19 at 21:58
  • Thank you. I can able to draw single path using polyline. Is it possible to draw multiple polyline? – Udhra Jan 11 '19 at 10:32

0 Answers0