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
, eg color
, fillOpacity
, weight
, etc.
Eg
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.
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 asetClassName()
oradd
/removeClass
API would be more appropriate.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.