Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leaflet path: how can I set a css class?

Tags:

leaflet

Well the title says it all but here is some code so you see what i mean.

function eachFeature(feature, layer) {
     layer.on({
         mouseover: highlightFeature,
         mouseout: resetHighlight,
     });
}
geojson = L.geoJson(geojson_raw, { style: style, onEachFeature: eachFeature });
geojson.addTo(map);

geojson_raw is the geojson object which is held in a javascript variable. style is just the function that returns an object with some style attributes. highlightFeature / resetHighlight are functions to change these styles according to mousein/out events.

So this code works and I already know how to change styles by reacting on user events. But how can I set an actual css-classname on the paths that are created from my geojson data? Later in my code I would like to select paths by a specific classname.

UPDATE

2 years later I stumbled over this issue once again. And it took me 2 hours to solve the mystery. The accepted answer below does work, BUT there is a catch. It only works if you set the cssClass before you call addTo(map) on the layer. After finally digging it up in the source code it became clear that leaflet only sets the cssClass when each path gets initialised.

like image 659
mwallisch Avatar asked Jun 13 '13 11:06

mwallisch


People also ask

How do you add a CSS to a leaflet?

Import Leaflet CSS Suppose the file you want to write the map component is src/map. jsx , you can import the Leaflet CSS file directly by putting import "leaflet/dist/leaflet. css" at the top of src/map. jsx .


1 Answers

The code below will allow you to add a class after the paths are created by the geoJosn method with D3.

var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "your_class");

However, if you want to add them on creation using only leaflet, try returning them in the style(feature) method like this:

function style(feature) {
        return {
          weight: 1,
          opacity: .5,
          fillOpacity: 0.7,
          className: feature.properties.name_of_node
        };
}

That worked really well for me.

like image 75
Mr. Concolato Avatar answered Sep 21 '22 20:09

Mr. Concolato