What's new
99vfx.com | Premium Web Community Forum
🎉 Join the Community – It’s Free! Register a free account today to become a member!

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

Points 18
Solutions 0
BrilliantBrilliant is verified member.
‎6 Months of Service‎
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