OpenDataVisualizer/client/src/components/TrafficMap.tsx
Claudio Schaad 39a62255af Add Thurgau watercraft map (#2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-11-06 21:10:01 +00:00

165 lines
5.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import 'leaflet/dist/leaflet.css';
import L from 'leaflet';
import { useEffect, useRef } from 'react';
import type { DayView, Station } from '../api/traffic';
import { addSwisstopoBaseLayers, escapeHtml } from '../map/baseLayers';
import { FlowAnimator } from '../traffic/flowAnimator';
import { sumCounts } from '../traffic/vehicleClasses';
interface TrafficMapProps {
stations: Station[];
day: DayView | null;
hour: number;
selectedCode: number | null;
onSelect: (code: number) => void;
onAnimatorReady: (animator: FlowAnimator) => void;
}
const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1];
const DATA_ATTRIBUTION =
'<a href="https://data.tg.ch/explore/dataset/dbu-tba-1/">Kanton Thurgau</a>';
export function TrafficMap({
stations,
day,
hour,
selectedCode,
onSelect,
onAnimatorReady,
}: TrafficMapProps) {
const containerRef = useRef<HTMLDivElement>(null);
const mapRef = useRef<L.Map | null>(null);
const animatorRef = useRef<FlowAnimator | null>(null);
const roadsRef = useRef<L.LayerGroup | null>(null);
const markersRef = useRef<Map<number, L.CircleMarker>>(new Map());
const onSelectRef = useRef(onSelect);
onSelectRef.current = onSelect;
const fittedRef = useRef(false);
const dayRef = useRef(day);
dayRef.current = day;
useEffect(() => {
if (!containerRef.current) {
return;
}
const map = L.map(containerRef.current, { zoomSnap: 0.5 }).setView(THURGAU_CENTER, 10);
addSwisstopoBaseLayers(map, DATA_ATTRIBUTION);
const canvas = document.createElement('canvas');
canvas.className = 'flow-canvas';
map.getContainer().appendChild(canvas);
roadsRef.current = L.layerGroup().addTo(map);
const animator = new FlowAnimator(map, canvas);
animator.start();
mapRef.current = map;
animatorRef.current = animator;
onAnimatorReady(animator);
const resizeObserver = new ResizeObserver(() => map.invalidateSize());
resizeObserver.observe(containerRef.current);
return () => {
resizeObserver.disconnect();
animator.dispose();
map.remove();
mapRef.current = null;
animatorRef.current = null;
markersRef.current.clear();
};
}, [onAnimatorReady]);
useEffect(() => {
const map = mapRef.current;
const roads = roadsRef.current;
if (!map || !roads) {
return;
}
roads.clearLayers();
markersRef.current.forEach((marker) => marker.remove());
markersRef.current.clear();
for (const station of stations) {
for (const direction of station.directions.slice(0, 1)) {
if (direction.path.length >= 2) {
L.polyline(direction.path, {
color: '#334155',
weight: 5,
opacity: 0.18,
interactive: false,
}).addTo(roads);
}
}
const marker = L.circleMarker([station.lat, station.lon], {
radius: 5,
color: '#0f172a',
weight: 1.5,
fillColor: '#ffffff',
fillOpacity: 0.85,
})
.on('click', () => {
onSelectRef.current(station.code);
if (map.getZoom() < 14) {
map.flyTo([station.lat, station.lon], 15, { duration: 0.8 });
}
})
.addTo(map);
markersRef.current.set(station.code, marker);
}
animatorRef.current?.setStations(stations);
animatorRef.current?.setDay(dayRef.current);
if (stations.length > 0 && !fittedRef.current) {
fittedRef.current = true;
map.fitBounds(L.latLngBounds(stations.map((s) => [s.lat, s.lon] as L.LatLngTuple)), {
padding: [40, 40],
});
}
}, [stations]);
useEffect(() => {
animatorRef.current?.setDay(day);
}, [day]);
useEffect(() => {
const hourIndex = Math.min(23, Math.max(0, hour));
const dayByStation = new Map(day?.stations.map((s) => [s.code, s]) ?? []);
for (const station of stations) {
const marker = markersRef.current.get(station.code);
if (!marker) {
continue;
}
const stationDay = dayByStation.get(station.code);
const perDirection = station.directions.map((direction) => {
const hours = stationDay?.directions.find((d) => d.direction === direction.name)?.hours;
return { name: direction.name, total: sumCounts(hours?.[hourIndex]) };
});
const total = perDirection.reduce((sum, d) => sum + d.total, 0);
const selected = station.code === selectedCode;
marker.setRadius(3 + Math.sqrt(total) / 6);
marker.setStyle({
color: selected ? '#dc2626' : '#0f172a',
weight: selected ? 3 : 1.5,
fillColor: selected ? '#fee2e2' : '#ffffff',
});
marker.bindTooltip(
`<strong>${escapeHtml(station.name)}</strong><br/>` +
`${escapeHtml(station.road)} · ${String(hourIndex).padStart(2, '0')}:00–${String(hourIndex + 1).padStart(2, '0')}:00<br/>` +
perDirection
.map((d) => `${escapeHtml(d.name)}: <strong>${d.total}</strong> Fz/h`)
.join('<br/>'),
{ direction: 'top', offset: [0, -6] },
);
}
}, [stations, day, hour, selectedCode]);
return <div ref={containerRef} className="traffic-map" />;
}