diff --git a/src/routePlanner/index.tsx b/src/routePlanner/index.tsx index 9edde40..69bf26d 100644 --- a/src/routePlanner/index.tsx +++ b/src/routePlanner/index.tsx @@ -8,13 +8,32 @@ import { nanoid } from 'nanoid'; export const RoutePlanner = () => { const [markers, setMarkers] = useState([]); + + const onMarkerRemove = useMemo( + () => (keyToRemove: string) => + setMarkers((markers) => + markers + .filter(({ key }) => key !== keyToRemove) + .map((marker, i) => ({ ...marker, index: i + 1 })), + ), + [], + ); + const onMapClick = useMemo( - () => (coordinates: Coordinates) => + () => (coordinates: Coordinates) => { + const key = nanoid(10); + const remove = () => onMarkerRemove(key); setMarkers((markers) => [ ...markers, - { coordinates, key: nanoid(10) }, - ]), - [], + { + key, + index: markers.length + 1, + remove, + coordinates, + }, + ]); + }, + [onMarkerRemove], ); return ( diff --git a/src/routePlanner/map.tsx b/src/routePlanner/map.tsx index d71bda0..8483081 100644 --- a/src/routePlanner/map.tsx +++ b/src/routePlanner/map.tsx @@ -71,8 +71,9 @@ export const MapComponent = ({ markers, onMapClick }: InternalMapProps) => { } layers.push( - ...markers.flatMap((marker, i) => { + ...markers.flatMap((marker) => { const circle = leaflet.circleMarker(marker.coordinates, { + bubblingMouseEvents: false, color: 'black', fill: true, fillOpacity: 100, @@ -84,11 +85,13 @@ export const MapComponent = ({ markers, onMapClick }: InternalMapProps) => { permanent: true, direction: 'center', className: 'text', - content: `${i + 1}`, + content: `${marker.index}`, }, circle, ) .setLatLng(marker.coordinates); + + circle.on('click', marker.remove); return [circle, tooltip]; }), ); @@ -100,6 +103,7 @@ export const MapComponent = ({ markers, onMapClick }: InternalMapProps) => { return () => { for (const layer of layers) { layer.removeFrom(map); + layer.remove(); } }; }, [mapRef, markers]); diff --git a/src/routePlanner/markers.tsx b/src/routePlanner/markers.tsx index e5369fd..a087e05 100644 --- a/src/routePlanner/markers.tsx +++ b/src/routePlanner/markers.tsx @@ -7,8 +7,11 @@ export const MarkersComponent = ({ markers }: InternalProps) => { <>

Markers

    - {markers.map(({ key }, i) => ( -
  1. {`Waypoint ${i + 1}`}
  2. + {markers.map((marker) => ( +
  3. + {`Waypoint ${marker.index}`} + +
  4. ))}
diff --git a/src/routePlanner/types.ts b/src/routePlanner/types.ts index eab1cd0..cc618f6 100644 --- a/src/routePlanner/types.ts +++ b/src/routePlanner/types.ts @@ -4,6 +4,8 @@ export type Coordinates = LatLng; export type Marker = { key: string; + remove: () => void; + index: number; coordinates: Coordinates; }; @@ -14,3 +16,7 @@ export type InternalProps = { export type InternalMapProps = InternalProps & { onMapClick: (coordinates: Coordinates) => void; }; + +export type MarkerListElementProps = { + marker: Marker; +};