Small preact-based (like React.js) project https://inga-lovinde.github.io/static/komoot-demo/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

92 lines
2.6 KiB

import leaflet from 'leaflet';
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 = 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]);
useEffect(() => {
const map = mapRef.current;
if (!map) {
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];
}),
];
for (const layer of layers) {
layer.addTo(map);
}
return () => {
for (const layer of layers) {
layer.removeFrom(map);
layer.remove();
}
};
}, [mapRef, markers]);
return <div ref={mapContainerRef} class="map-container" />;
};