0

I'm using geoJson in a featureLayer so I can use the setFilter-Function. My question is: How can I use the setStyle-Function and give Elements with different properties different colors?

My Code:

var jsonLayer = L.mapbox.featureLayer(geoJson).addTo(map);
//Filter for start_year
jsonLayer.setFilter(function(f){return f.properties["start_date"] <=outyear;})
jsonLayer.setStyle(getStyle(this));

function getStyle(feature){return{
stroke: '#555555',
strokewidth: 1,
fillColor: getColor(feature)}};

function getColor(feature){
    if (feature.properties.start_date<="1700"){return "#c78432"};
    else if (feature.properties.start_date>="1800"){return "#F9A63F";}
    else {return "#B8B8B8"};}

This obviously does not work correctly.

3

Use the setStyle() method to set the style for all features, and use the eachLayer() method to set the style by feature.

So, something like:

var jsonLayer = L.mapbox.featureLayer(geoJson).addTo(map);

// set style for all features
jsonLayer.setStyle({stroke: '#555555',
                    strokewidth: 1});

// set style by feature
jsonLayer.eachLayer(function(layer){
    var fillColor = "#B8B8B8"
    if (layer.feature.properties.start_date<="1700"){
      fillColor = "#c78432";
    } else if (layer.feature.properties.start_date>="1800"){
      fillColor = "#F9A63F";
    }
    layer.setStyle({
      fillColor: fillColor
      ... (other Path style options)
    });
});

Of course, you don't need the first jsonLayer.setStyle() if you already know you are going to set the style at the feature level.

Haven't tested this, but should work.

| improve this answer | |
  • Thank you very much!! That works perfectly. Note: There is a missing = in else if after fillColor. – hno2 Mar 23 '15 at 20:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.