implemented useMap custom hook

main
Inga 🏳‍🌈 6 months ago
parent e48de70750
commit a4f642d232
  1. 40
      src/routePlanner/hooks/useMap/index.ts
  2. 35
      src/routePlanner/map.tsx

@ -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:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
})
.addTo(map);
mapRef.current = map;
return () => {
map.remove();
};
}, [mapContainerRef, mapRef, viewParameters]);
return mapRef;
};

@ -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<typeof useMap>[1];
export const MapComponent = ({ markers, onMapClick }: MapProps) => {
const mapContainerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<leaflet.Map | undefined>(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:
'&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
})
.addTo(map);
mapRef.current = map;
return () => {
map.remove();
};
}, []);
const mapRef = useMap(mapContainerRef, defaultMapViewParameters);
useEffect(() => {
const map = mapRef.current;

Loading…
Cancel
Save