parent
e48de70750
commit
a4f642d232
@ -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<Ref<HTMLElement>>, |
||||
viewParameters: Parameters<Map['setView']>, |
||||
) => { |
||||
const mapRef = useRef<leaflet.Map | undefined>(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: |
||||
'© <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>', |
||||
}) |
||||
.addTo(map); |
||||
|
||||
mapRef.current = map; |
||||
|
||||
return () => { |
||||
map.remove(); |
||||
}; |
||||
}, [mapContainerRef, mapRef, viewParameters]); |
||||
|
||||
return mapRef; |
||||
}; |
Loading…
Reference in new issue