Search code examples
leafletleaflet.drawreact-leaflet

React-Leaflet-Draw: accessing a polygon's array of coordinates on save


I've got a component which puts an editable polygon on the map. When the user hits the "save" button, I want to access an array of the polygon's new vertices, so that I can save them. How do I do this?

My component:

<FeatureGroup>
    <EditControl
        position="topright"
        onEdited={e => console.log(e)}
        edit={{ remove: false }}
        draw={{
                marker: false,
                circle: false,
                rectangle: false,
                polygon: false,
                polyline: false
             }}
        />
        <Polygon positions={polygonCoords} />;
</FeatureGroup>

The couple of references I've got:

https://github.com/alex3165/react-leaflet-draw

https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html#l-draw-event-draw:editstop

I understand I have to implement some sort of function dealing with the onEdited hook and the event generated thereby, but does anyone have any idea how I can get the new vertex array from this event?


Solution

  • For anyone else struggling with this, here's a working solution with ES6:

            <FeatureGroup>
                <EditControl
                    position="topright"
    
                    //this is the necessary function. It goes through each layer
                    //and runs my save function on the layer, converted to GeoJSON 
                    //which is an organic function of leaflet layers.
    
                    onEdited={e => {
                        e.layers.eachLayer(a => {
                            this.props.updatePlot({
                                id: id,
                                feature: a.toGeoJSON()
                            });
                        });
                    }}
                    edit={{ remove: false }}
                    draw={{
                        marker: false,
                        circle: false,
                        rectangle: false,
                        polygon: false,
                        polyline: false
                    }}
                />
                <Polygon positions={[positions(this.props)]} />;
            </FeatureGroup>
        );