Created
August 1, 2022 11:24
-
-
Save MrMeison/5fec32108934556784b9a789a0d6e2ee to your computer and use it in GitHub Desktop.
leaflet useMap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {useEffect, useState, MutableRefObject} from 'react'; | |
import {Map, TileLayer} from 'leaflet'; | |
import {City} from '../types/city'; | |
function useMap( | |
mapRef: MutableRefObject<HTMLElement | null>, | |
city: City | |
): Map | null { | |
const [map, setMap] = useState<Map | null>(null); | |
const { location } = city; | |
useEffect(() => { | |
if (mapRef.current === null) { | |
return; | |
} | |
const instance = new Map(mapRef.current, { | |
center: { | |
lat: location.latitude, | |
lng: location.longitude | |
}, | |
zoom: location.zoom | |
}); | |
const layer = new TileLayer( | |
'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png', | |
{ | |
attribution: | |
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>' | |
} | |
); | |
instance.addLayer(layer); | |
// eslint-disable-next-line no-console | |
console.log('create map'); | |
setMap(instance); | |
return () => { | |
setMap(null); | |
instance.remove(); | |
}; | |
}, [mapRef, location]); | |
return map; | |
} | |
export default useMap; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment