I got a small app that use the Direction Service feature of Google Map. It is working well, I can change routes, but I have a small problem, where a user could go back to a
You could also use:
directionsDisplay.setDirections({routes: []});
In this way, you can keep using one map with one renderer for all routes.
The other answers did not work for me. I found a solution from this question
define directionsDisplay
only 1 time(outside of the click
-handler)
I had similar problem, I tried with directionsDisplay.setMap(null);
but it didn’t work.
The problem was the directionsDisplay
object which I created was declared locally.
I changed it to global and every time the function is called, it will use the same global directionsDisplay
object and make changes to it. This will definitely remove the previous route displayed on same object.
It's important - at least it was in my case - that while directionsDisplay
can be declared globally the instance has to be created after the map object otherwise it gave a reference error
var map;
var directionsDisplay;
function initMap() {
map = new google.maps.Map(...);
directionsDisplay = new google.maps.DirectionsRenderer(...);
}
function yourFunction() {
// your code
directionsDisplay.addListener(...);
}
This is the fix
// Clear past routes
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
Since on each call, new instance of DirectionRenderer created thats why each new instance is unaware of previous instance.
Move
var directionsDisplay = new google.maps.DirectionsRenderer();
to the global(at the top where all other Global variables have been initialized.)
By doing so, each time you would be using single instance of DirectionRenderer.