-1

I'm using this example to add markers on my direction A to B. How can I remove "old" markers, when I add new start and end points. I try to change gmarkers[j].setMap(null); but not working.

for (var j=0; j< gmarkers.length; j++) {
      if (boxes[i].contains(gmarkers[j].getPosition()))
          gmarkers[j].setMap(map);
  }

fiddle/original code from this question

Community
  • 1
  • 1
onlinepch
  • 109
  • 3
  • 13
  • What are the markers for? I see that you verify that your boxes do contain them, but I don't understand why. – ffflabs Aug 19 '14 at 15:14

3 Answers3

1

You use the setVisible function:

var marker = new google.maps.Marker({
position: new google.maps.LatLng(10, -10), 
map: map
}); 

marker.setVisible(false);

in your case:

for (var j=0, m; m = gmarkers[j]; j++)
{
    m.setVisible(false);
}

With .setMap() you kind of loose the reference; setVisible() toggles the marker

best

M

mboeckle
  • 938
  • 13
  • 29
  • This answer works as well. You should add that this path requires the original code to be modified to use setVisible(true) when re-enabling the markers. – ffflabs Aug 19 '14 at 15:23
1

Got it. You have a clearBoxes function. You can use it to clear the markers as well.

function clearBoxes() {
  if (boxpolys != null) {
    for (var i = 0; i < boxpolys.length; i++) {
      boxpolys[i].setMap(null);
    }
  }
  for (var j=0; j< gmarkers.length; j++) {
      gmarkers[j].setMap(null);
  }
  boxpolys = null;
}
ffflabs
  • 17,166
  • 5
  • 51
  • 77
0

To clear the markers, do this (set their map property to null):

for (var i=0;i<gmarkers.length;i++){
  gmarkers[i].setMap(null);
}

updated fiddle

geocodezip
  • 158,664
  • 13
  • 220
  • 245