【问题标题】:How to pass 2 values to json style in leaflet如何在传单中将 2 个值传递给 json 样式
【发布时间】:2016-11-04 11:31:32
【问题描述】:

我需要通过 2 种样式,我目前有:

第一种风格:

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

我做的:

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

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

leaflet docs if this can help, here

【问题讨论】:

  • 您需要发送 2 个不同/单独的值还是两个值的组合?
  • @aManHasNoName 一个组合。然而我得到了解决方案并将其粘贴在下面
  • 好的。您也可以检查$.extend 来组合对象值。

标签: javascript jquery json leaflet geojson


【解决方案1】:

这是解决方案:

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

【讨论】:

    【解决方案2】:

    不熟悉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;
    }
    ...
    

    【讨论】:

      【解决方案3】:
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 2021-07-23
      • 2015-10-22
      • 1970-01-01
      相关资源
      最近更新 更多