简体   繁体   中英

How to change geojson style by clicking a button

Hello based on this leaflet tutorial http://leafletjs.com/examples/choropleth.html I am trying to create 20 buttons so that I can change line : fillColor:getColor(feature.properties.density) to sth different (for example by pressing btn #1 fillColor:getColor(feature.properties.btn1), btn #2 fillColor:getColor(feature.properties.btn1), etc

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

All I want is when a button is pressed, a different geojson property to be displayed.

Something along these lines

First, turn your layer into a variable

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

Create a new function for getting the new style based on your buttons id

function newStyle(id) {
    return {
        fillColor: getColor(id),
        weight: 2,
        opacity: 1,
        color: 'white',
        dashArray: '3',
        fillOpacity: 0.7
    };
}

Then listen for the click and get the btn id and set the new style

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

UPDATE:

Updated the getcolor to only be getColor(id). You should make your buttons correspond to the colors in the getColor function on the example. So id="11" will return #FED976 from the example, id="21" will return #FEB24C and so on.

Alternatively you could just set your button ids to the color (id="#FED976") and then change the fillColor: getColor(id) to 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;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM