问题
I use geocoding to allow the user to navigate to a specific place and then add markers in a specific radius to this navigated point. If the user clicks on the button again and wants to navigate to another place it should remove all the markers of the first request. I have to say that the navigated point is marked with a blue marker and the others are marked with a red marker. I use this code to do it:
// global
var previousTarget = 0;
var markers = new Array(); // All my markers are stored here
// end global
geocoder.geocode(
{'address': address},
function(results, status){
if(status == google.maps.GeocoderStatus.OK){
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: 'http://maps.google.com/mapfiles/ms/micons/blue.png'
});
var marker, i;
var splitted = locations.splitted(",");
for(var i = 0; i < splitted.length; i++){
geocoder.geocode(
{'address': splitted[i]},
function(results, status){
if(results != null){
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i){
return function() {
$.ajax({
url: 'myfile.php',
type: 'POST',
data: {addrData: jqXHR.responseText},
success: function(datas, textStatus, jqXHR){
for(var l = 0; l < markers.length; l++){
if(marker == markers[l]){
infowindow.setContent('test');
infowindow.open(map, marker);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert("Error");
}
});
}
})(marker, i));
}
}
);
if(previousTarget > 1){ // Here is the function to click the button twice
markers.setMap(null);
}
}
}
}
);
If I do this there comes an error in the console by hitting the button twice:
Uncaught TypeError: Object [object Array] has no method 'setMap'
And if I change markers to marker it just removes the blue marker. Can someone please give me a hint where I made an error?
回答1:
You need to loop through your markers array and remove each marker.
for (var i=0; i<markers.length; i++) {
markers[i].setMap(null);
}
来源:https://stackoverflow.com/questions/21333453/remove-google-maps-markers-by-click-button-again-using-javascript