如何通过单击按钮更改geojson样式

时间:2013-11-10 23:57:40

标签: javascript leaflet

Hello基于这个传单教程http://leafletjs.com/examples/choropleth.html我试图创建20个按钮,以便我可以更改行: fillColor:getColor(feature.properties.density)与sth不同(例如通过按btn#1 fillColor:getColor(feature.properties.btn1), btn#2 fillColor:getColor(feature.properties.btn1)等

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

L.geoJson(statesData, {style: style}).addTo(map);

我想要的只是按下一个按钮,显示不同的geojson属性。

1 个答案:

答案 0 :(得分:5)

沿着这些方向的东西

首先,将您的图层变为变量

var mylayer = L.geoJson(statesData, {style: style});
map.addLayer(mylayer);

根据按钮ID

创建一个新功能来获取新样式
function newStyle(id) {
    return {
        fillColor: getColor(id),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7
    };
}

然后听取点击并获取btn id并设置新样式

$('body').on('click', 'btn', function (btn) {
    var id = $(btn).attr('id');
    var new_style = newStyle(id);
    mylayer.setStyle(new_style);
});

更新:

将getcolor更新为getColor(id)。您应该使您的按钮与示例中getColor函数中的颜色相对应。所以id =“11”将从示例中返回#FED976,id =“21”将返回#FEB24C,依此类推。

或者您可以将按钮ID设置为颜色(id =“#FED976”),然后将fillColor:getColor(id)更改为fillColor:id

UPDATE2:

function style1(feature) {
    return {
        fillColor: getColor(feature.properties.btn1)
    };
}

function style2(feature) {
    return {
        fillColor: getColor(feature.properties.btn2)
    };
}

var mylayer = L.geoJson(statesData, {style: style});
map.addLayer(mylayer);

$('body').on('click', 'btn', function (btn) {
    var id = $(btn).attr('id');
    switch (id) {
        case "btn1":
            map.removeLayer(mylayer);
            mylayer = L.geoJson(statesData, {style: style1});
            map.addLayer(mylayer);
            break;
        case "btn2":
            map.removeLayer(mylayer);
            mylayer = L.geoJson(statesData, {style: style2});
            map.addLayer(mylayer);
            break;
    }
});