OpenDataVisualizer/client/src/components/TrafficMap.tsx
Claudio Schaad 7b65926aa2 Add Thurgau traffic visualizer and start page (#1)
- Thurgau hourly traffic counts (data.tg.ch) refreshed every 6 h into a per-day JSON cache
- Road geometry per station direction from swisstopo swissTLM3D; roundabout arms run outward from the roundabout centre
- Leaflet map with animated vehicles by class, time controls and base map switcher (grey, colour, aerial)
- Station panel with per-class counts and Chart.js charts
- Start page with map tiles; traffic map at /verkehr/thurgau
- Dockerfile and docker-compose, xUnit tests

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 20:17:26 +00:00

192 lines
6.2 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 { 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 BASE_MAP_STORAGE_KEY = 'odv.baseMap';
const ATTRIBUTION =
'&copy; <a href="https://www.swisstopo.admin.ch/">swisstopo</a> · Daten: <a href="https://data.tg.ch/explore/dataset/dbu-tba-1/">Kanton Thurgau</a>';
const BASE_MAPS = [
{ name: 'Grau', layer: 'ch.swisstopo.pixelkarte-grau', maxNativeZoom: 18 },
{ name: 'Farbe', layer: 'ch.swisstopo.pixelkarte-farbe', maxNativeZoom: 18 },
{ name: 'Luftbild', layer: 'ch.swisstopo.swissimage', maxNativeZoom: 19 },
];
function createBaseLayers(): Record<string, L.TileLayer> {
return Object.fromEntries(
BASE_MAPS.map((baseMap) => [
baseMap.name,
L.tileLayer(
`https://wmts.geo.admin.ch/1.0.0/${baseMap.layer}/default/current/3857/{z}/{x}/{y}.jpeg`,
{ maxZoom: 19, maxNativeZoom: baseMap.maxNativeZoom, attribution: ATTRIBUTION },
),
]),
);
}
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);
const baseLayers = createBaseLayers();
const storedBaseMap = localStorage.getItem(BASE_MAP_STORAGE_KEY);
(baseLayers[storedBaseMap ?? ''] ?? baseLayers[BASE_MAPS[0].name]).addTo(map);
L.control.layers(baseLayers, undefined, { position: 'topright' }).addTo(map);
map.on('baselayerchange', (event: L.LayersControlEvent) =>
localStorage.setItem(BASE_MAP_STORAGE_KEY, event.name),
);
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" />;
}
function escapeHtml(value: string): string {
return value.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
}