James Conkling
James Conkling

Reputation: 3663

Set layer className within event callback in Leaflet

I'm looking to set a geojson feature's style via setting its className. This works perfectly fine if placed directly on the feature like so:

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        layer.setStyle({className: 'grid-cell'});
    }
}).addTo(map);

with the style defined in a .css file

path.grid-cell{
  stroke-opacity: 1;
  stroke: #444;
  fill: #aaa;
}

However, it does not work if added within a feature's event callback:

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        layer.on('click', function(e){
          this.setStyle({className: 'grid-cell'});
          this.bringToFront();
        });
    }
}).addTo(map);

What's surprising is that setStyle({<style_options>}); work in either case for every other L.path option besides className, e.g. color, fillOpacity, weight, etc.

E.g.

L.geoJson(geojson, {
    onEachFeature: function (feature, layer) {
        // this works
        layer.setStyle({color: '#faa', fillOpacity: 0.4, weight: 1});

        // this works too
        layer.setStyle({className: 'grid-cell'});

        layer.on('click', function(e){
          // and this works
          layer.setStyle({color: '#afa', fillOpacity: 0.4, weight: 2});

          // BUT THIS DOES NOT WORK
          this.setStyle({className: 'grid-cell'});
          this.bringToFront();
        });
    }
}).addTo(map);

Any idea what's up here? Here's a plunker illustrating the issue.

Upvotes: 5

Views: 1966

Answers (1)

Mourner
Mourner

Reputation: 3301

For a discussion of this issue, look here: https://github.com/Leaflet/Leaflet/issues/2662. One of the comments:

I don't think setStyle should actually change the className. The class is not really a style property, and the logic necessary to handle leaflet- classes seems like a hack. I think a setClassName() or add/removeClass API would be more appropriate.

Upvotes: 4

Related Questions