diff --git a/src/routePlanner/getLayersForMarkers.ts b/src/routePlanner/hooks/useMarkersOnMap/getLayersForMarkers.ts similarity index 96% rename from src/routePlanner/getLayersForMarkers.ts rename to src/routePlanner/hooks/useMarkersOnMap/getLayersForMarkers.ts index 9ecf5a6..7c2b90e 100644 --- a/src/routePlanner/getLayersForMarkers.ts +++ b/src/routePlanner/hooks/useMarkersOnMap/getLayersForMarkers.ts @@ -1,5 +1,5 @@ import leaflet from 'leaflet'; -import { Marker } from './types'; +import { Marker } from '../../types'; export const getLayersForMarkers = (markers: Marker[]) => [ // lines diff --git a/src/routePlanner/hooks/useMarkersOnMap/index.ts b/src/routePlanner/hooks/useMarkersOnMap/index.ts new file mode 100644 index 0000000..5a63deb --- /dev/null +++ b/src/routePlanner/hooks/useMarkersOnMap/index.ts @@ -0,0 +1,29 @@ +import leaflet from 'leaflet'; +import { Ref, useEffect } from 'preact/hooks'; +import { getLayersForMarkers } from './getLayersForMarkers'; +import { Marker } from '../../types'; + +export const useMarkersOnMap = ( + mapRef: Readonly>, + markers: Marker[], +) => { + useEffect(() => { + const map = mapRef.current; + if (!map) { + return; + } + + const layers = getLayersForMarkers(markers); + + for (const layer of layers) { + layer.addTo(map); + } + + return () => { + for (const layer of layers) { + layer.removeFrom(map); + layer.remove(); + } + }; + }, [mapRef, markers]); +}; diff --git a/src/routePlanner/map.tsx b/src/routePlanner/map.tsx index 6c85be7..4b82b9f 100644 --- a/src/routePlanner/map.tsx +++ b/src/routePlanner/map.tsx @@ -1,9 +1,9 @@ -import { useEffect, useRef } from 'preact/hooks'; +import { useRef } from 'preact/hooks'; import { MapProps } from './types'; import { useMap } from './hooks/useMap'; import { useMapClick } from './hooks/useMapClick'; -import { getLayersForMarkers } from './getLayersForMarkers'; +import { useMarkersOnMap } from './hooks/useMarkersOnMap'; const defaultMapViewParameters = [ [47.42111, 10.98528], @@ -14,26 +14,7 @@ export const MapComponent = ({ markers, onMapClick }: MapProps) => { const mapContainerRef = useRef(null); const mapRef = useMap(mapContainerRef, defaultMapViewParameters); useMapClick(mapRef, onMapClick); - - useEffect(() => { - const map = mapRef.current; - if (!map) { - return; - } - - const layers = getLayersForMarkers(markers); - - for (const layer of layers) { - layer.addTo(map); - } - - return () => { - for (const layer of layers) { - layer.removeFrom(map); - layer.remove(); - } - }; - }, [mapRef, markers]); + useMarkersOnMap(mapRef, markers); return
; };