diff --git a/src/routePlanner/hooks/useMapClick/index.ts b/src/routePlanner/hooks/useMapClick/index.ts new file mode 100644 index 0000000..a5d6609 --- /dev/null +++ b/src/routePlanner/hooks/useMapClick/index.ts @@ -0,0 +1,26 @@ +import leaflet from 'leaflet'; +import { Ref, useEffect } from 'preact/hooks'; + +import 'leaflet/dist/leaflet.css'; +import { Coordinates } from '../../../shared/types'; + +export const useMapClick = ( + mapRef: Readonly>, + onMapClick: (leaflet: Coordinates) => void, +) => { + useEffect(() => { + const map = mapRef.current; + if (!map) { + return; + } + + const handler: leaflet.LeafletMouseEventHandlerFn = ({ latlng }) => { + onMapClick(latlng); + }; + map.on('click', handler); + + return () => { + map.removeEventListener('click', handler); + }; + }, [mapRef, onMapClick]); +}; diff --git a/src/routePlanner/map.tsx b/src/routePlanner/map.tsx index 6139011..38240b8 100644 --- a/src/routePlanner/map.tsx +++ b/src/routePlanner/map.tsx @@ -4,6 +4,7 @@ import { MapProps } from './types'; import 'leaflet/dist/leaflet.css'; import { useMap } from './hooks/useMap'; +import { useMapClick } from './hooks/useMapClick'; const defaultMapViewParameters = [ [47.42111, 10.98528], @@ -13,21 +14,7 @@ const defaultMapViewParameters = [ export const MapComponent = ({ markers, onMapClick }: MapProps) => { const mapContainerRef = useRef(null); const mapRef = useMap(mapContainerRef, defaultMapViewParameters); - - useEffect(() => { - const map = mapRef.current; - if (!map) { - return; - } - - const handler: leaflet.LeafletMouseEventHandlerFn = ({ latlng }) => - onMapClick(latlng); - map.on('click', handler); - - return () => { - map.removeEventListener('click', handler); - }; - }, [mapRef, onMapClick]); + useMapClick(mapRef, onMapClick); useEffect(() => { const map = mapRef.current;