implemented useMarkersOnMap

main
Inga 🏳‍🌈 1 year ago
parent aec4d090f3
commit 04e340ad64
  1. 2
      src/routePlanner/hooks/useMarkersOnMap/getLayersForMarkers.ts
  2. 29
      src/routePlanner/hooks/useMarkersOnMap/index.ts
  3. 25
      src/routePlanner/map.tsx

@ -1,5 +1,5 @@
import leaflet from 'leaflet';
import { Marker } from './types';
import { Marker } from '../../types';
export const getLayersForMarkers = (markers: Marker[]) => [
// lines

@ -0,0 +1,29 @@
import leaflet from 'leaflet';
import { Ref, useEffect } from 'preact/hooks';
import { getLayersForMarkers } from './getLayersForMarkers';
import { Marker } from '../../types';
export const useMarkersOnMap = (
mapRef: Readonly<Ref<leaflet.Map | undefined>>,
markers: Marker[],
) => {
useEffect(() => {
const map = mapRef.current;
if (!map) {
return;
}
const layers = getLayersForMarkers(markers);
for (const layer of layers) {
layer.addTo(map);
}
return () => {
for (const layer of layers) {
layer.removeFrom(map);
layer.remove();
}
};
}, [mapRef, markers]);
};

@ -1,9 +1,9 @@
import { useEffect, useRef } from 'preact/hooks';
import { useRef } from 'preact/hooks';
import { MapProps } from './types';
import { useMap } from './hooks/useMap';
import { useMapClick } from './hooks/useMapClick';
import { getLayersForMarkers } from './getLayersForMarkers';
import { useMarkersOnMap } from './hooks/useMarkersOnMap';
const defaultMapViewParameters = [
[47.42111, 10.98528],
@ -14,26 +14,7 @@ export const MapComponent = ({ markers, onMapClick }: MapProps) => {
const mapContainerRef = useRef<HTMLDivElement>(null);
const mapRef = useMap(mapContainerRef, defaultMapViewParameters);
useMapClick(mapRef, onMapClick);
useEffect(() => {
const map = mapRef.current;
if (!map) {
return;
}
const layers = getLayersForMarkers(markers);
for (const layer of layers) {
layer.addTo(map);
}
return () => {
for (const layer of layers) {
layer.removeFrom(map);
layer.remove();
}
};
}, [mapRef, markers]);
useMarkersOnMap(mapRef, markers);
return <div ref={mapContainerRef} class="map-container" />;
};

Loading…
Cancel
Save