问题
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...
回答1:
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);
回答2:
You could also use:
directionsDisplay.setDirections({routes: []});
In this way, you can keep using one map with one renderer for all routes.
回答3:
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.
回答4:
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)
回答5:
This is the fix
// Clear past routes
if (directionsDisplay != null) {
directionsDisplay.setMap(null);
directionsDisplay = null;
}
回答6:
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.
回答7:
set strokeWeight: 0 then polyline will hide
回答8:
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(...);
}
来源:https://stackoverflow.com/questions/5232756/remove-route-with-google-map