diff --git a/src/components/Map/index.jsx b/src/components/Map/index.jsx index cff2fa12b..a18e01ce7 100644 --- a/src/components/Map/index.jsx +++ b/src/components/Map/index.jsx @@ -97,22 +97,35 @@ const LeaftletMap = ({ const className = getBEMClassName('leaflet-map', modifiers); const onFeatureCreate = event => { - onGeoJsonFeatureSet(event.layer.toGeoJSON()); + updateGeoJsonFeature(event.layer); + }; + + const onFeatureDelete = () => { + // The value `null` is needed to make sure that Formio actually updates the value. + // node_modules/formiojs/components/_classes/component/Component.js:2528 + onGeoJsonFeatureSet(null); }; const onSearchMarkerSet = event => { - onGeoJsonFeatureSet(event.marker.toGeoJSON()); + updateGeoJsonFeature(event.marker); }; - useEffect(() => { - if (!featureGroupRef.current) { - return; + const updateGeoJsonFeature = newFeatureLayer => { + if (featureGroupRef.current) { + const newFeatureLayerId = newFeatureLayer._leaflet_id; + const layers = featureGroupRef.current?.getLayers(); + // Limit the amount of features to 1, by removing the previous layer + if (layers.length > 1) { + const oldLayerIds = layers + .map(layer => layer._leaflet_id) + .filter(layerId => layerId !== newFeatureLayerId); + oldLayerIds.forEach(oldLayerId => { + featureGroupRef.current?.removeLayer(oldLayerId); + }); + } } - // Remove the old layers and add the new one. - // This limits the amount of features to 1 - featureGroupRef.current?.clearLayers(); - featureGroupRef.current?.addLayer(Leaflet.geoJSON(geoJsonFeature)); - }); + onGeoJsonFeatureSet(newFeatureLayer.toGeoJSON()); + }; return ( <> @@ -139,9 +152,9 @@ const LeaftletMap = ({