From a4f642d232b2cbc9268100facbec8fff25df8c82 Mon Sep 17 00:00:00 2001 From: Inga Date: Sun, 19 Nov 2023 03:08:36 +0000 Subject: [PATCH] implemented useMap custom hook --- src/routePlanner/hooks/useMap/index.ts | 40 ++++++++++++++++++++++++++ src/routePlanner/map.tsx | 35 +++++----------------- 2 files changed, 47 insertions(+), 28 deletions(-) create mode 100644 src/routePlanner/hooks/useMap/index.ts 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;