Skip to content

Instantly share code, notes, and snippets.

@MrMeison
Created August 1, 2022 11:24
Show Gist options
  • Save MrMeison/5fec32108934556784b9a789a0d6e2ee to your computer and use it in GitHub Desktop.
Save MrMeison/5fec32108934556784b9a789a0d6e2ee to your computer and use it in GitHub Desktop.
leaflet useMap
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:
'&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <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