diff --git a/src/routePlanner/hooks/useMap/index.ts b/src/routePlanner/hooks/useMap/index.ts new file mode 100644 index 0000000..83992f5 --- /dev/null +++ b/src/routePlanner/hooks/useMap/index.ts @@ -0,0 +1,40 @@ +import leaflet, { type Map } from 'leaflet'; +import { Ref, useEffect, useRef } from 'preact/hooks'; + +import 'leaflet/dist/leaflet.css'; + +export const useMap = ( + mapContainerRef: Readonly>, + viewParameters: Parameters, +) => { + const mapRef = useRef(undefined); + + useEffect(() => { + if (mapRef.current) { + return; + } + + if (!mapContainerRef.current) { + return; + } + + const map = leaflet.map(mapContainerRef.current); + map.setView(...viewParameters); + + leaflet + .tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { + maxZoom: 19, + attribution: + '© OpenStreetMap', + }) + .addTo(map); + + mapRef.current = map; + + return () => { + map.remove(); + }; + }, [mapContainerRef, mapRef, viewParameters]); + + return mapRef; +}; diff --git a/src/routePlanner/map.tsx b/src/routePlanner/map.tsx index b94545f..6139011 100644 --- a/src/routePlanner/map.tsx +++ b/src/routePlanner/map.tsx @@ -3,37 +3,16 @@ import { useEffect, useRef } from 'preact/hooks'; import { MapProps } from './types'; import 'leaflet/dist/leaflet.css'; +import { useMap } from './hooks/useMap'; + +const defaultMapViewParameters = [ + [47.42111, 10.98528], + 13, +] satisfies Parameters[1]; export const MapComponent = ({ markers, onMapClick }: MapProps) => { const mapContainerRef = useRef(null); - const mapRef = useRef(undefined); - - useEffect(() => { - if (mapRef.current) { - return; - } - - if (!mapContainerRef.current) { - return; - } - - const map = leaflet.map(mapContainerRef.current); - map.setView([47.42111, 10.98528], 13); - - leaflet - .tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { - maxZoom: 19, - attribution: - '© OpenStreetMap', - }) - .addTo(map); - - mapRef.current = map; - - return () => { - map.remove(); - }; - }, []); + const mapRef = useMap(mapContainerRef, defaultMapViewParameters); useEffect(() => { const map = mapRef.current;