[google-maps] Google Map API - Removing Markers

I've tried looking at a large variety of code blocks here and on the Google Maps API documentation but STILL have not been able to figure out how to hide markers.

This is the current code that I am using, and it worked for one instance. Once I added the "for" loop in the function with markers.setMap(null) Firefox displays the following error:

Error: TypeError: markers.setMap is not a function

function removeMarkers(){
    var markers;
    alert(markers);
    alert(locations.length);
    for (i = 0; i<locations.length; i++){
        markers = locations[i];
        alert(markers.title);
        markers.setMap(null);
    }
}

Additional Information: Campus Map and full code (excluding Map API)

This question is related to google-maps google-maps-api-3

The answer is


According to Google documentation they said that this is the best way to do it. First create this function to find out how many markers there are/

   function setMapOnAll(map1) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map1);
    }
  }

Next create another function to take away all these markers

 function clearMarker(){
setMapOnAll(null);
}

Then create this final function to erase all the markers when ever this function is called upon.

 function delateMarkers(){
clearMarker()
markers = []
//console.log(markers) This is just if you want to

}

Hope that helped good luck


You can try this

    markers[markers.length-1].setMap(null);

Hope it works.


Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.

export default function useGoogleMapMarker(props) {
  const [marker, setMarker] = useState();

  useEffect(() => {
    // ...code
    const marker = new maps.Marker({ position, map, title, icon });
    // ...code
    setMarker(marker);
    return () => marker.setMap(null); // to remove markers when unmounts
  }, []);

  return marker;
}