Reputation: 3580
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?
Upvotes: 6
Views: 7409
Reputation: 338
Getting this took me some hours so it might be helpful to someone someday. First initialise mapLayer state to hold your coordinates and implement onCreated() and onEdited() functions
const [mapLayers, setMapLayers] = useState([]); const onCreated = e => { console.log(e) const {layerType, layer} = e if (layerType === "polygon") { const {leaflet_id} = layer setMapLayers(layers => [...layers, {id: leaflet_id, latlngs: layer.getLatLngs()[0]}]) } }; const onEdited = e => { // console.log('Edited data', e); const {layers: {_layers}} = e; Object.values(_layers).map(( {_leaflet_id, editing}) => { setMapLayers((layers) => layers.map((l) => l.id === _leaflet_id? {...l, latlngs: {...editing.latlngs[0]} } : l) ) }); };
Upvotes: 1
Reputation: 3580
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>
);
Upvotes: 4