-1

I have a function that pins marker in Google Map. This is how it looks:

// Look to draw marker in various coordinates. Pseudo code...
for(var i = 1; i <= noOfCoordinates; i++){

   var lat = latitude[i];
   var long = longitude[i];

   drawMarker(lat, long);

};

var drawMarker = function(lat, long){
// code to draw marker

marker.setMap(map);

};

But I also have a function to remove those markers

for(var i = 1; i <= noOfCoordinates; i++){

   removeMarker(null);

};

var removeMarker = function(map){
// code to draw marker

marker.setMap(map);

};

drawmarker(); pins/draws marker in google map but removeMarker(); does not remove all markers from the google map, it only removes last one.

I want to remove all marker associated with it, that was drawn from drawMarker(); function. Remove = hide, not delete.

how can I fix this?

asax
  • 237
  • 6
  • 21

1 Answers1

0

Keep references to all the markers, call .setMap(null) on each one

geocodezip suggests like this:

markers = []; // <-- global variable

for(var i = 1; i <= noOfCoordinates; i++){

   var lat = latitude[i];
   var long = longitude[i];

   var marker = drawMarker(lat, long);
   markers[i].push(marker);
};

var drawMarker = function(lat, long){
// code to draw marker

  marker.setMap(map);
  return marker;
};

for(var i = 1; i <= noOfCoordinates; i++){

   markers[i].setMap(null);

};
wf9a5m75
  • 6,100
  • 3
  • 25
  • 59
  • I did that but it does not delete the markers. I also get error: TypeError: Cannot read property 'setMap' of undefined – asax Nov 11 '16 at 02:28
  • Also I get this error: InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama ... js?key={{...... there is some key here....}}:34 InvalidValueError: – asax Nov 11 '16 at 02:28
  • The variable `markers` have to be global variable – wf9a5m75 Nov 11 '16 at 02:47
  • I made it global. It still does not remove markers. – asax Nov 11 '16 at 02:55