Reputation: 1250
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 list of markers after tracing a route.
I can't find a way to delete routes with google map. For markers I store them and do setMap(null)
, do not see a way here...
Upvotes: 31
Views: 53441
Reputation: 449
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(...);
}
Upvotes: 1
Reputation: 546
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.
Upvotes: 7
Reputation: 147
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.
Upvotes: 1
Reputation: 1655
This is the fix
// Clear past routes
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
Upvotes: 8
Reputation: 1782
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)
Upvotes: 9
Reputation: 19738
You could also use:
directionsDisplay.setDirections({routes: []});
In this way, you can keep using one map with one renderer for all routes.
Upvotes: 63
Reputation: 23977
if you are using DirectionsRenderer to display the routes, you can call setMap(null) on it too. That way you delete the displayed route.
Using the example code here http://code.google.com/apis/maps/documentation/javascript/examples/directions-simple.html
just call
directionsDisplay.setMap(null);
Upvotes: 34