How to remove all Google maps marker using Javascript?


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.

 


Asked by:- bhanu
2
: 3017 At:- 3/28/2022 8:42:42 AM
Javascript Google maps remove markers







1 Answers
profileImage Answered by:- vikas_jk

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

2
At:- 3/28/2022 9:42:28 AM
Thanks for helpful answer and fiddle it helps, and working as needed. 0
By : bhanu - at :- 3/28/2022 1:07:46 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use