如何在传单中传递2个值到json样式

How to pass 2 values to json style in leaflet

本文关键字:json 样式 2个 单中传      更新时间:2023-09-26

我需要传递2个样式,我目前有:

第一风格:

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);

但是忽略了第一个style

我尝试将其作为数组传递:

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

但是,第一个样式被忽略了。

传单文档如果有帮助,请点击这里

解决方案:

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);

不熟悉leaflet,但是从js的角度来看,使用重复键肯定会用最后一个键条目覆盖它的值。

如果你想附加style1和style2,因为style的两个函数都返回一个对象,你可以通过$.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;
}
...

您在对象初始化器中放入了重复的键。没有。

参见如何动态生成具有重复键的JSON对象?查找JavaScript对象中的重复键