Clear Google Maps API markers through JavaScript

I am playing around with the Google Maps API v3 for a project I am building. I have managed to place markers on the map at the location the user clicks at however I want to have a clear all button to remove all the markers. I have looked at various answers on here and tried different methods. I have also consulted the Google Maps API documentation however all the methods I have tried do not work. It should be noted the map can have multiple markers.

The code I have is below:

///The function addLatLng is called when the user clicks on the Map
   function addLatLng(event) {

  // This code adds the marker to the map
  var marker = new google.maps.Marker({
    position: event.latLng,
    title: '#' + path.getLength(),

map: map



   ///The clearall function is called when a button is clicked
function clearall() {
    poly.setMap(null);//This clears the polyline that is drawn and works correctly


Any help would be appreciated


According to Google Maps API doc calling setMap only remove the marker from the map but not delete it. If you want to delete multiple markers, you could do as in Google Maps API example given :

1/ When adding a marker, pushing it in an array

2/ To remove all markers : create a function that takes this array as an argument, and apply setMap() on each of the array's element through a for loop.

3/ To delete all markers (i.e from memory) after remove : create a function to call setMap(null) on each marker in your array (which according to Google delete the marker) and delete all the markers from your array (e.g. markersArray = [])

You can find corresponding google example code in my second reference.

Need Your Help

Web.config with XDT transform to do partial replace

c# visual-studio-2012 web-config .net-4.5 web.config-transform

I am in a situation where I just want to update a part of a the URL of a WCF endpoint. Right now we do this by including different configs with all the endpoints per 'variety'. This is tedious to m...

loaded the “rootView” nib but didn't get a UITableView.'


I have developed a split view based applicaiton. And i am trying to add image to root view controller.