JSFiddle - React, Tailwind, and code Playground
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.6.0/leaflet.js"></script>
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src/Leaflet.Editable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/react-leaflet.min.js"></script>
<div id="app"></div>
CSS
body {
margin: 0;
}
.leaflet-container {
height: 100vh;
}
.active {
background: red;
color: white;
}
Babel + JSX
const { Map: LeafletMap, TileLayer, Polygon } = ReactLeaflet;
class App extends React.Component {
state = {
mapOptions: {
center: [ 43.1249, 1.254 ],
zoom: 15,
editable: true,
},
editing: null,
polygons: [
[
[ 43.1292, 1.256 ],
[ 43.1295, 1.259 ],
[ 43.1291, 1.261 ],
],
[
[ 43.1239, 1.259 ],
[ 43.123, 1.263 ],
[ 43.1252, 1.265 ],
[ 43.1250, 1.261 ],
],
[
[ 43.1239, 1.244 ],
[ 43.123, 1.253 ],
[ 43.1252, 1.255 ],
[ 43.1250, 1.251 ],
[ 43.1239, 1.244 ],
],
],
}
mapRef = React.createRef()
polygonRefs = []
onClick = e => {
const index = +e.target.dataset.index;
const refs = this.polygonRefs;
this.setState(({ editing }) => {
refs.forEach((n, i) => {
const method = i === index && editing !== index
? 'enableEdit'
: 'disableEdit';
n.leafletElement[method]();
});
// перейти к редактируемому полигону
//this.mapRef.current.leafletElement.fitBounds(refs[index].leafletElement.getBounds());
return {
editing: editing === index ? null : index,
};
});
}
onLoad = e => {
e.target.on('editable:disable', this.onEditEnd);
}
onEditEnd = ({ layer }) => {
this.setState(({ polygons }) => ({
polygons: polygons.map((n, i) => i === layer.options.index
? layer.getLatLngs().map(n => n.map(Object.values))
: n
),
}));
}
render() {
const { polygons, editing } = this.state;
const refs = this.polygonRefs = [];
return (
<div>
{polygons.map((n, i) =>
<button
data-index={i}
className={editing === i ? 'active' : ''}
onClick={this.onClick}
>edit #{i}</button>
)}
<LeafletMap
{...this.state.mapOptions}
ref={this.mapRef}
whenReady={this.onLoad}
...