Manuel
Manuel

Reputation: 2542

Cannot toggle markers Google Maps API v3

hey i have a problem to toggle my markers on/off

Do you have any idea why it toggles only one marker (marker "Freilichtmuseum") ?

thX for Help !!

var locations = [
    ['Sensenwerk', 47.20031715397146, 15.338023278873152, 4],
    ['Freilichtmuseum', 47.158075170093, 15.315393984492403, 5],
];


var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
    });

    function toggleLayer() {     
        if (marker.getMap() === null) {
            marker.setMap(map);
        }
        else {
            marker.setMap(null);
        }

    }
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}

Upvotes: 1

Views: 2323

Answers (1)

geocodezip
geocodezip

Reputation: 161334

toggleLayer only toggles the current "marker". If you want it to do more than the last one, you need to save references to all the markers that need to be toggled in an array and iterate through that array.

var markers = [];
for (i = 0; i < locations.length; i++) {  
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
    });
    markers.push(marker);
    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}

    function toggleLayer() {     
      for (var i=0; i< markers.length; i++){
        if (markers[i].getMap() === null) {
            markers[i].setMap(map);
        }
        else {
            markers[i].setMap(null);
        }
      }
    }

working fiddle

Upvotes: 3

Related Questions