I have a project where I need to display routes between 2 markers. I found this post which I customized and it works quite well (thanks a lot for it BTW): Google Maps Api straight (shortest) route
Now when the user selects another address/marker, the new routes are displayed, but the old ones remain there too, so obviously I need to get rid of them before rendering the new ones. I struggled for days, but I keep getting all kinds of errors. (I admit, my JS skill is still average...)
I think the bit that renders them is this:
//painting the routes in green blue and red
routesResponses.forEach(function (res) {
res.routes.forEach(function (rou, index) {
new google.maps.DirectionsRenderer({
// directionsRenderer({
map: map,
directions: res,
routeIndex: index,
polylineOptions: {
strokeColor:
rou.legs[0].duration.value == fastest
? "red"
: rou.legs[0].distance.value == shortest
? "darkgreen"
: "blue",
strokeOpacity:
rou.legs[0].duration.value == fastest
? 0.8
: rou.legs[0].distance.value == shortest
? 0.9
: 0.5,
strokeWeight:
rou.legs[0].duration.value == fastest
? 9
: rou.legs[0].distance.value == shortest
? 8
: 3,
},
});
});
});
But because there is "new google.maps.DirectionsRenderer" inside foreach loop, I don't know how to get those objects and remove them.
I tried moving the new google.maps.DirectionsRenderer
above in the global scope, but then I get an error "Uncaught TypeError: directionsRenderer is not a function".