What's new
  • Do not create multi-accounts, you will be blocked! For more information about rules, limits, and more, visit the Help Page Found a dead link? Use the report button!
  • If no files are available, please contact me or reply in the thread. I will update them immediately.

Leaflet: I can add class, but I can't add style to GeoJSON

In Leaflet, when you add a GeoJSON layer, styling and classes can be managed, but they work differently. To add style directly, you should use the style option or provide a style function when creating the L.geoJSON layer. However, if you're trying to dynamically apply a CSS class, that might need a workaround because GeoJSON styling is done inline.

Here’s how to resolve your issue:

Adding Styles

You can define styles for the GeoJSON using the style option:

JavaScript:
L.geoJSON(geojsonData, {

  style: function(feature) {

    return {

      color: 'blue', // Line color

      weight: 2, // Line thickness

      fillColor: 'yellow',// Fill color for polygons

      fillOpacity: 0.5 // Fill opacity

    };

  }

}).addTo(map);

Adding Classes

Leaflet doesn't directly support adding a className to GeoJSON features, but you can use the onEachFeature option with setStyle to manipulate DOM elements:

JavaScript:
L.geoJSON(geojsonData, {

  onEachFeature: function(feature, layer) {

    // Access the layer and its DOM element

    if (layer instanceof L.Path) {

      layer.setStyle({

        className: 'custom-class' // Add a custom class

      });

    }

  }

}).addTo(map);

Make sure you define the class in your CSS:
JavaScript:
.custom-class {

  stroke: red;

  stroke-width: 2px;

  fill: green;

  fill-opacity: 0.5;

}

Note on className and Inline Styles

If you're using className inside style, it appends a class to the SVG path for your features.

Inline styles (e.g., color, weight) take precedence over CSS rules. If you want to rely entirely on CSS, avoid defining inline styles in the style option.


Debugging Tips

Check the browser’s developer tools to see if the class is being applied.

Ensure that Leaflet version supports className (it was introduced in Leaflet 1.0.0 for Path elements).
 
Back
Top