implemented useMapClick custom hook

main
Inga 🏳‍🌈 6 months ago
parent a4f642d232
commit 99ce0d97e1
  1. 26
      src/routePlanner/hooks/useMapClick/index.ts
  2. 17
      src/routePlanner/map.tsx

@ -0,0 +1,26 @@
import leaflet from 'leaflet';
import { Ref, useEffect } from 'preact/hooks';
import 'leaflet/dist/leaflet.css';
import { Coordinates } from '../../../shared/types';
export const useMapClick = (
mapRef: Readonly<Ref<leaflet.Map | undefined>>,
onMapClick: (leaflet: Coordinates) => void,
) => {
useEffect(() => {
const map = mapRef.current;
if (!map) {
return;
}
const handler: leaflet.LeafletMouseEventHandlerFn = ({ latlng }) => {
onMapClick(latlng);
};
map.on('click', handler);
return () => {
map.removeEventListener('click', handler);
};
}, [mapRef, onMapClick]);
};

@ -4,6 +4,7 @@ import { MapProps } from './types';
import 'leaflet/dist/leaflet.css';
import { useMap } from './hooks/useMap';
import { useMapClick } from './hooks/useMapClick';
const defaultMapViewParameters = [
[47.42111, 10.98528],
@ -13,21 +14,7 @@ const defaultMapViewParameters = [
export const MapComponent = ({ markers, onMapClick }: MapProps) => {
const mapContainerRef = useRef<HTMLDivElement>(null);
const mapRef = useMap(mapContainerRef, defaultMapViewParameters);
useEffect(() => {
const map = mapRef.current;
if (!map) {
return;
}
const handler: leaflet.LeafletMouseEventHandlerFn = ({ latlng }) =>
onMapClick(latlng);
map.on('click', handler);
return () => {
map.removeEventListener('click', handler);
};
}, [mapRef, onMapClick]);
useMapClick(mapRef, onMapClick);
useEffect(() => {
const map = mapRef.current;

Loading…
Cancel
Save