0

How can I delete specific marker in google maps ? I tried code below but I get TypeError: marker[1] is undefined error. Without [1] it deletes the first marker only.

google.maps.event.addDomListener(deletemark, 'click', function() {
          marker[1].setMap(null);
});
}

(from the comments, slightly edited) This is how I create markers, and marker's lat,long in array

var locations = [ [56.066877,21.069274], [55.279849,26.048155] ]; // removed "hanging comma"
for (i = 0; i < locations.length; i++) 
{
  marker = new MarkerWithLabel({
    position: new google.maps.LatLng(locations[i][0], locations[i][1]), 
    map: map // removed "hanging comma"
  });
} // added missing close bracket 
geocodezip
  • 158,664
  • 13
  • 220
  • 245
user1876234
  • 857
  • 2
  • 14
  • 28
  • What does your code that defines your markers look like? Do you have references to any but the first? How does your code know which marker is the "specific" one to delete? – geocodezip May 03 '13 at 20:09
  • This is how I create markers, and marker's lat,long in array `for (i = 0; i < locations.length; i++) { marker = new MarkerWithLabel({ position: new google.maps.LatLng(locations[i][0], locations[i][1]), map: map, });` `var locations = [ [56.066877,21.069274], [55.279849,26.048155], ];` – user1876234 May 03 '13 at 20:20
  • 1
    It would be much better if you edited your question with the additional information, it is really hard to read code posted in comments. – geocodezip May 03 '13 at 21:37

2 Answers2

3

try using an array to store markers,

var markerArray=[];
var locations = [ [56.066877,21.069274], [55.279849,26.048155] ];
for (i = 0; i < locations.length; i++) 
{
 marker = new MarkerWithLabel({
 position: new google.maps.LatLng(locations[i][0], locations[i][1]), 
 map: map // removed "hanging comma"
 });
markerArray.push(marker);
} /

and for deleting markers,

function deleteMarkers() {
  if (markersArray) {
  for (i in markersArray) {
   markersArray[i].setMap(null);
  }
markersArray.length = 0;
}
}
  • avoid for..in loop on javascripts, http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea – Lee Gary Feb 21 '14 at 01:35
1

Your issue is that you have one marker variable, left pointing to the last marker you create (not the first). If you want to delete other markers, you need to keep references to them (either in an array or by using function closure).

geocodezip
  • 158,664
  • 13
  • 220
  • 245