Petey
Petey

Reputation: 3337

How to change the style of a feature collection in leaflet?

I was looking at the choropleth example.

https://leafletjs.com/examples/choropleth/

This is the data source they use

{
 "type": "Feature",
 "properties": {
    "name": "Alabama",
    "density": 94.65
 },
 "geometry": ...
...
 }

My dataset is a feature collection of polygons so it looks like

{
"type": "Feature Collection",
"Features": [
     {
 "type": "Feature",
 "properties": {
    "name": "Alabama",
    "density": 94.65
 },
 "geometry": ...
...
 },
     {
 "type": "Feature",
 "properties": {
    "name": "Ohio",
    "density": 99.65
 },
 "geometry": ...
...
 },
   }

Anyway so its an array so when i make my style function I use

const finalLayer = L.geoJSON(currentLayer.layer, { 
style: {this.styleData(currentLayer.layer)}
           });
           this.currentProjectLayers.push(finalLayer);
           finalLayer.addTo(this.map);

getColor(data) {
return data > 1000000 ? '#800026' :
      data > 800000 ? '#BD0026' :
      data > 600000 ?  '#E31A1C' :
      data > 400000 ?  '#FC4E2A' :
      data > 200000 ? '#FD8D3C' :
        '#FEB24C';
}

styleData(feature) {
return {
  fillColor: this.getColor(feature.features[0].properties.totalHH),
  weight: 2,
  opacity: 1,
  color: 'white',
  dashArray: '3',
  fillOpacity: 0.7
};
} 

Obviously i don't want to use 0 as the index. When I use the index it colors them all according to the index of the one spot. I know how to do a forEach but I don't think that will work. I need to do the style in an onEachFeature i think.... But can I apply the style using OnEachFeature.. how would I do that?

Upvotes: 4

Views: 2573

Answers (1)

ghybs
ghybs

Reputation: 53185

You are probably trying to work around an issue that does not exist.

Although that may not be explicit, Leaflet GeoJSON factory also parses GeoJSON Feature Collection, as if it were directly an array of Features. As such, each of those Features will be modified by the style option, which receives as argument the Feature data:

L.geoJSON(geojsonFeatureCollectionObject, {
  style: function (featureObject) {
    return {
      fill: featureObject.properties.totalHH
    };
  }
});

Upvotes: 3

Related Questions