0

I need to pass 2 styles, i currently have:

First style:

function style(feature) {
    return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7,
        fillColor: getColor(feature.properties.density)
    };
}

The I do:

var classNameMap = <?php echo JSON_encode($classesForCountries); ?>;
geojson = L.geoJson(statesData, {
    style: style,
    style: function(feature) {
        var classes = classNameMap[feature.properties.name];
        return {className: classes};
    },
        onEachFeature: onEachFeature
}).addTo(map);

But that ignores the first style

I tried by passing it as an array:

geojson = L.geoJson(statesData, {
    style: [style, function(){
        var classes = classNameMap[feature.properties.name];
        return {className: classes};
    }],
        onEachFeature: onEachFeature
}).addTo(map);

But yet, first style is ignored.

leaflet docs if this can help, here

rob.m
  • 9,843
  • 19
  • 73
  • 162

3 Answers3

2

This is the solution:

var classNameMap = <?php echo JSON_encode($classesForCountries); ?>;
function style(feature) {
    var classes = classNameMap[feature.properties.name];
    return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7,
        fillColor: getColor(feature.properties.density),
        className: classes
    };
}

geojson = L.geoJson(statesData, {
    style: style,
        onEachFeature: onEachFeature
}).addTo(map);
rob.m
  • 9,843
  • 19
  • 73
  • 162
2

Not familiar with leaflet, but looking from js perspective using duplicate key will definitely override its value with the last key entry.

If you are trying append the style1 and style2, since both the functions of style returns an object, you can do so by $.extend.

function style_1(feature) {
    return {
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7,
        fillColor: getColor(feature.properties.density)
    };
}

...
style: function(feature) {
    // Now the logic is a simple hashmap look-up
    var style1 = style_1(feature);
    var classes = classNameMap[feature.properties.name];
    var finalStyle = $.extend(style1, {className: classes});
    return finalStyle;
}
...
n4m31ess_c0d3r
  • 3,028
  • 5
  • 26
  • 35
0

You're putting duplicate keys in the object initializer. Don't.

See How to generate a JSON object dynamically with duplicate keys? , Finding duplicate keys in JavaScript object

IvanSanchez
  • 18,272
  • 3
  • 30
  • 45