Hello, I was able to
add multiple markers using javascript in google maps, but now I would like to remove them without reloading google maps. I was able to remove one using 'marker.setMap(null);
' but how can I remove all markers at once using Javascript in Google Maps.
You can create a seperate function and call it on button click or as per your needs to remove all markers in an array
function removeMarkers(){
//loop through all markers and remove it.
for(var i=0; i < markers.length; i++){
markers[i].setMap(null);
}
markers = [];
}
In above case, we are considering 'markers
' as an array.
Complete code
var LocationsForMap = [
['Delhi',28.704060, 77.102493],
['Jaipur',26.9124, 75.7873],
['London', 51.507351, -0.127758],
['Washington', 47.751076,-120.740135]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(28.704, 77.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var markers =[];
var i;
for (i = 0; i < LocationsForMap.length; i++) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(LocationsForMap[i][1], LocationsForMap[i][2]),
map: map
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: LocationsForMap[i][0]
});
markers.push(newmarker);
}
function removeMarkers(){
//loop through all markers and remove it.
for(var i=0; i < markers.length; i++){
markers[i].setMap(null);
}
markers = [];
}
and here is the fiddle
https://jsfiddle.net/yLsxgmhu/1/
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly