John Deligiannis
John Deligiannis

Reputation: 53

Set Style on geojson file Leaflet

I cannot restyle a geojson file that has been added to the map. I have a function to getcolor which depends on a value on the geojson file.

    function getColor(d) {
    return d > 20 ? '#d53e4f' :
        d > 15 ? '#fc8d59' :
        d > 13 ? '#fee08b' :
        d > 10 ? '#e6f598' :
        d > 5 ? '#99d594' :
        d > 0 ? '#3288bd' :
        '#FFEDA0';
    }

In the file, I have 5 fields: d2014, d2015, d2016, d2017, d2018 with integers. The file is a js created with QGIS Create webMap plugin. On page load I add the geojson with a style of 2016:

    layer_europe = new L.geoJson(json_europe, {
      style: Cstyle2016,

      onEachFeature: pop_europe_data,

    });
mymap.addLayer(layer_europe);

The function of style is:

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

I have 5 of those functions for each year.

In addition, I have a range that has values from 2014-2018. I would like every time I change the value of the range to change the colors of the polygons.

I have until now on range:

    function changecolors(value){
        var a = document.getElementById('textInput').value = value        
        const st = "Cstyle" + a;
    }

The setStyle does not work.

Sample of geojson file:

    var json_europe = {
    "type": "FeatureCollection",
    "name": "europe_all_0",
    "crs": { "type": "name", "properties": { "name": 
    "urn:ogc:def:crs:OGC:1.3:CRS84" } },
    "features": [
    { "type": "Feature", "properties": { "CNTR_ID": "AL", "NAME_ENGL": 
    "Albania", "d2014": 9.50571, "d2015": 12.88267, "d2016": 12.65591, 
    "d2017": 7.6109, "d2018": 10.80788 }, "geometry": { "type": 
    "MultiPolygon", "coordinates": [bla bla bla] }]

Thanks in advance!!!

Upvotes: 0

Views: 2251

Answers (1)

IvanSanchez
IvanSanchez

Reputation: 19059

One approach is to create several instances of L.GeoJson, one per symbolization, e.g....

layer_europe_2016 = new L.geoJson(json_europe, { style: Cstyle2016 });
layer_europe_2017 = new L.geoJson(json_europe, { style: Cstyle2017 });
layer_europe_2018 = new L.geoJson(json_europe, { style: Cstyle2018 });

...and hide/show them appropriately, e.g.:

function changecolors(value){
    var a = document.getElementById('textInput').value = value        

    layer_europe_2016.remove();
    layer_europe_2017.remove();
    layer_europe_2018.remove();

    if (a === 2016) { layer_europe_2016.addTo(map); }
    if (a === 2017) { layer_europe_2017.addTo(map); }
    if (a === 2018) { layer_europe_2018.addTo(map); }
}

Upvotes: 2

Related Questions