Leaflet GeoJSON Styling – How to Change the Color of GeoJSON Layer

geojsonleafletstyle

I want to show my road network in red color. How can I change this default color of the road network. Where should I attach style property?

var roadNetwork = new L.LayerGroup();
$.getJSON("{% url 'road_dataset' %}", function (data) {
    var geojson = L.geoJson(data, {
        onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.road_name);
        }
    });
    geojson.addTo(roadNetwork);
});

Best Answer

You don't use jquery for this, jquery is a library for interacting with the DOM. You just have to define a style object and attach it to your layer, as seen in the documentation:

var roadNetwork = new L.LayerGroup();

var myStyle = { // Define your style object
    "color": "#ff0000"
};

$.getJSON("{% url 'road_dataset' %}", function (data) {
    var geojson = L.geoJson(data, {

        style: myStyle, // Assign the style object to the "style" property of the layer

        onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.road_name);
        }
    });
    geojson.addTo(roadNetwork);
});