React-Leaflet change GEOJSON shape color by state

2019-05-20 00:54发布

Through an API call, I get GEOJSON data (points) . I immediately display that data in the leaflet map by using circleMaker and display them all to be one color. I then give the user the option to slide a slider ( triggers action with payload being the slider value/location). What I want to do is change the color of some circles ( i.e one those who have an attribute that is lower that the slider value). How can I do this without re-rendering all circles?

Example: ( all circles are green and slider value is at 0, I then change the slider to 4 and all the circles that have a value (that I get from the GEOJSON features) lower than 4 ( slider value) change color to red, and the rest stay the same.

Sample Code: I have a GEOJSON component:

 <GeoJSON
  key={_.uniqueId()}
  data= {this.props.countrySelected.geojson}
  pointToLayer={this.pointToLayer.bind(this)}
  ></GeoJSON>

^ The data is a GEOJSON object with all points that have a feature of lets say "score"

Here is pointToLayer:

pointToLayer = (feature, latlng) => {
return L.circleMarker(latlng, {
  color: '#228B22',
  fillColor: '#228B22',
  fillOpacity: .6,
  radius: 3
}).bindPopup(popUpString(feature.properties)); 
}

In another component I have a slider that calls handleChange everytime it is changed:

handleChange = (value) => {
this.props.sliderChanged(value);
}

This then triggers an action, that then triggers a reducer that makes the adequate changes to the state ( i.e. it makes the state slider value change to the value in the slider that the user just changed.

1条回答
Lonely孤独者°
2楼-- · 2019-05-20 01:41

Check out these two links to get some context for the solution I've come up with:

https://github.com/PaulLeCam/react-leaflet/issues/382

http://leafletjs.com/reference-1.2.0.html#geojson

You will need to create a renderGeojson function like this which will be re-evaluated every re-render:

function renderCountries(countryGeoJson, sliderValue) {
  return countryGeoJson.map(country => {
    let style = () => { color: 'defaultColor' };

    if (country.score < sliderValue ) {
      style = () => { color: 'red' };
    } else if ( country.score > slidervalue ) {
      style = () => { color: 'green' };

    return (
      <GeoJSON key={field.id} data={field.geoJson} style={style} />
    );
  });
}

Now, this function will be called in the actual render function in your component which will be called every time slider value changes.

Pseudo-code but something like:

<Map>
   { renderCountries( this.props.countrySelected.geojson, this.state.sliderValue ) }
</Map>

Make sense? :)

查看更多
登录 后发表回答