react-leaflet add layers dynamically
Asked Answered
M

2

11

I'm starting to use react-leaflet and I came across a question: In my application the user fills out a form that then requests a rest service that returns a GeoJSON, which is then added as a new layer on my map. My question: How do I implement adding layers dynamically in react-leaflet?

Thank you.

Memphian answered 29/1, 2017 at 18:44 Comment(0)
J
3

The best approach is to create GeoJSON Layer wrapper for react-leaflet. There is a similar implementation of GeoJSON layer with clustering available in react-leaflet's plugins section. Then you should add this layer to your map component and change it's data when you need to. So there is no need to add the layer dynamically but dynamically change data for it. Check the leaflet's GeoJSON example to get the idea http://leafletjs.com/examples/geojson/.

The approach will work if you have one layer with changing data. But if you have different data sets you will need to add a GeoJSON layer for each of them.

<Map ...>
{this.props.datasets.map((ds, ix) => {
  return (<GeoJSONOverlay data={ds} key={ix} />);
})}
</Map>
Justen answered 20/2, 2017 at 9:1 Comment(1)
broken 'plugins section' link. Plugins.md -> plugins.mdAtwell
H
0

I have similar problem. I would like to clear and create marker layers dynamically. I think you can do it by getting reference to the actual map view react refs e.g.

<Map ref={Map => this.map = Map}>

later on you can then use this.map with normal Leaflet functions. Other option could be that you create layers in JSX same way I create markers:

{this.props.markers.map((i,index) => { return ( <Marker key={i} position={i}> <Popup> <span>Great marker!</span> </Popup> </Marker>); })}

Hollister answered 15/2, 2017 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.