leafletmarkers

setOpacity for multiple markers at the time


I'm using leaflet for my project and I want to use filter marker in it. To do it, I will setOpacity to 0 for all markers and re setOpacity to 1 for my targets. I know leaflet allow to setOpacity for each market but can I set all markers at the same time? Thanks for your help!


Solution

  • There are many ways to achieve that

    In leaftlet

    Create a layer group and add each marker to this group :

    var myGroup = L.layerGroup([mark1, mark2, ...]);
    

    You can add the entire group to the map.

    Then, when you want to set marker opacity to 0 do :

    myGroup.eachLayer(function(layer) {
        layer.setOpacity(0);
    });
    

    A little jsfiddle example here :

    https://jsfiddle.net/csblo/64phqLb7/4/

    In pure javascript

    Store all your markers in an array. First create an array :

    var allMarkers = [];
    

    And when you create a new marker push it in this array :

    var marker = L.marker(...);
    allMarkers.push(marker);
    

    Then, when you have to set opacity to 0 :

    allMarkers.forEach(function(marker) {
        marker.setOpacity(0);
    });