diff --git a/src/routePlanner/getLayersForMarkers.ts b/src/routePlanner/getLayersForMarkers.ts new file mode 100644 index 0000000..9ecf5a6 --- /dev/null +++ b/src/routePlanner/getLayersForMarkers.ts @@ -0,0 +1,43 @@ +import leaflet from 'leaflet'; +import { Marker } from './types'; + +export const getLayersForMarkers = (markers: Marker[]) => [ + // lines + ...markers.flatMap((thisMarker, i) => { + const previousMarker = markers[i - 1]; + if (!previousMarker) { + return []; + } + + return [ + leaflet.polyline([ + previousMarker.coordinates, + thisMarker.coordinates, + ]), + ]; + }), + // circles and labels + ...markers.flatMap((marker) => { + const circle = leaflet.circleMarker(marker.coordinates, { + bubblingMouseEvents: false, + color: 'black', + fill: true, + fillOpacity: 100, + radius: 10, + }); + const tooltip = leaflet + .tooltip( + { + permanent: true, + direction: 'center', + className: 'text', + content: marker.shortLabel, + }, + circle, + ) + .setLatLng(marker.coordinates); + + circle.on('click', marker.remove); + return [circle, tooltip]; + }), +]; diff --git a/src/routePlanner/map.tsx b/src/routePlanner/map.tsx index 38240b8..6c85be7 100644 --- a/src/routePlanner/map.tsx +++ b/src/routePlanner/map.tsx @@ -1,10 +1,9 @@ -import leaflet from 'leaflet'; import { useEffect, useRef } from 'preact/hooks'; import { MapProps } from './types'; -import 'leaflet/dist/leaflet.css'; import { useMap } from './hooks/useMap'; import { useMapClick } from './hooks/useMapClick'; +import { getLayersForMarkers } from './getLayersForMarkers'; const defaultMapViewParameters = [ [47.42111, 10.98528], @@ -22,46 +21,7 @@ export const MapComponent = ({ markers, onMapClick }: MapProps) => { return; } - const layers = [ - // lines - ...markers.flatMap((thisMarker, i) => { - const previousMarker = markers[i - 1]; - if (!previousMarker) { - return []; - } - - return [ - leaflet.polyline([ - previousMarker.coordinates, - thisMarker.coordinates, - ]), - ]; - }), - // circles and labels - ...markers.flatMap((marker) => { - const circle = leaflet.circleMarker(marker.coordinates, { - bubblingMouseEvents: false, - color: 'black', - fill: true, - fillOpacity: 100, - radius: 10, - }); - const tooltip = leaflet - .tooltip( - { - permanent: true, - direction: 'center', - className: 'text', - content: marker.shortLabel, - }, - circle, - ) - .setLatLng(marker.coordinates); - - circle.on('click', marker.remove); - return [circle, tooltip]; - }), - ]; + const layers = getLayersForMarkers(markers); for (const layer of layers) { layer.addTo(map);