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!
1 Answer
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);
});
-
I tried pure, just with the setIcon() function JS variation (even before I saw this forum, so I started to dig up) and it did not worked for me... I get error: marker.setOpacity is not a function ... Commented Sep 27, 2019 at 12:16
-
@la_femme_it Dobrý den, maybe "marker" object is not actually a marker type ?– csbloCommented Oct 1, 2019 at 11:47
-
it is. It did worked with leaflet built in functions :) Might be Zeppelin specific issue, I do not know. Javascript is waaay out of my league. Hezky den Commented Oct 1, 2019 at 11:48
-
For the future, for whatever reason,
m.setOpacity(NUM)
didn't work for me ("not a function"), even though that's what the docs say, but inspecting the marker element and usingm.setStyle({opacity: NUM})
worked. Commented Jun 17 at 2:05