Add css class to leaflet layer during runtime

I'm using leaflet to draw layers of circles (so there are several layers, each consisting of several circles) on a map.

I've saved all the layers on a featuregroup:

this.globalLayer = L.featureGroup();

I'm adding new circles to it by creating a new featuregroup of the circles, and adding the featuregroup to the globalLayer:

let circleLayer: L.featureGroup();

let point1 = L.circle([pos_lat, pos_long], {color: color, opacity: 1, 
radius: radius});
let point2 = L.circle([pos_lat, pos_long], {color: color, opacity: 1, 
radius: radius});
circleLayer.addLayer(point1);
circleLayer.addLayer(point2);
// etc.

this.globalLayer.addLayer(circleLayer);

Now I want to add a css class to some of the layers:

for (let cssLayer of cssLayers) { // cssLayers is a L.featureGroup[]
    this.globalLayer.removeLayer(cssLayer);
    cssLayer.setStyle({className: 'animate'});
    this.globalLayer.addLayer(cssLayer);
}

This works, but since the layers contain a lot of circles, this takes a while to compute. Is there a way to just add a css Class without removing and adding them again?

I've tried

this.globalLayer.eachLayer(layer => {
    layer.setStyle({className: 'animate'})
});

But setStyle() does not exist on type L.Layer

JsFiddle with my current, workaround solution

Upvotes: 4

Views: 2368

Answers (2)

Jesse Fried
Jesse Fried

Reputation: 21

I'm not sure if this is the best practice but I found that you can use the layer's _path attribute:

this.globalLayer.eachLayer(layer => {
    layer._path.classList.add('animate')
});

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 76436

You will need to add a class to the corresponding layer before you add it to other labels, like

circleLayer1.setStyle({className: 'myListener'});

and then you can find this class anytime you want:

$('#blink').click(function() {
    $(".myListener").addClass("blink");
});

Fiddle.

Upvotes: 3

Related Questions