From 383226ed4fc73307ccff0c5b1c87cf2562c7cd7b Mon Sep 17 00:00:00 2001 From: Claudio Schaad Date: Wed, 18 Nov 2026 19:08:09 +0000 Subject: [PATCH] Add combined Thurgau map with switchable layers (#5) - One shared Leaflet map (MapHost) with the traffic, watercraft and vehicle maps turned into layer components that attach to it and clean up on unmount; each layer adds its own data credit - Data loading and per-dataset state moved into hooks used by both the single pages and the combined page - /karte/thurgau: layer panel with on/off switch, controls and legend per dataset, shared year controls for the yearly layers, traffic day/time controls, layers and year in the URL - Side panel shows the selected municipality, harbour or station, or an overview of all active layers; the municipality panel lists the counting stations and harbours in that municipality - Start page shows only the combined map; single maps are linked from the layer cards - Docs: combined map in docs/datasets.md and CLAUDE.md Co-Authored-By: Claude Opus 5.5 Co-authored-by: Claudio Schaad Co-committed-by: Claudio Schaad --- CLAUDE.md | 8 +- client/public/previews/combined-thurgau.svg | 62 +++ client/public/previews/traffic-thurgau.svg | 74 --- client/public/previews/vehicles-thurgau.svg | 40 -- client/public/previews/watercraft-thurgau.svg | 85 ---- client/src/App.tsx | 2 + .../{TrafficMap.tsx => TrafficLayer.tsx} | 56 +-- client/src/components/combined/LayerCard.tsx | 44 ++ client/src/components/combined/LayerPanel.tsx | 21 + .../combined/MunicipalityContext.tsx | 81 +++ .../src/components/combined/OverviewPanel.tsx | 119 +++++ .../components/vehicles/MunicipalityPanel.tsx | 5 + .../{VehicleMap.tsx => VehicleLayer.tsx} | 68 ++- ...{WatercraftMap.tsx => WatercraftLayer.tsx} | 45 +- client/src/map/MapHost.tsx | 48 ++ client/src/map/baseLayers.ts | 7 +- client/src/map/geometry.ts | 88 ++++ client/src/map/mapContext.ts | 24 + client/src/map/useYearPlayback.ts | 45 ++ client/src/maps.ts | 32 +- client/src/pages/ThurgauCombinedPage.tsx | 476 ++++++++++++++++++ client/src/pages/TrafficThurgauPage.tsx | 147 ++---- client/src/pages/VehiclesThurgauPage.tsx | 100 +--- client/src/pages/WatercraftThurgauPage.tsx | 113 +---- client/src/styles.css | 214 +++++++- client/src/traffic/useTrafficData.ts | 119 +++++ client/src/vehicles/useVehicleData.ts | 48 ++ client/src/watercraft/useWatercraftData.ts | 72 +++ docs/datasets.md | 16 + 29 files changed, 1655 insertions(+), 604 deletions(-) create mode 100644 client/public/previews/combined-thurgau.svg delete mode 100644 client/public/previews/traffic-thurgau.svg delete mode 100644 client/public/previews/vehicles-thurgau.svg delete mode 100644 client/public/previews/watercraft-thurgau.svg rename client/src/components/{TrafficMap.tsx => TrafficLayer.tsx} (77%) create mode 100644 client/src/components/combined/LayerCard.tsx create mode 100644 client/src/components/combined/LayerPanel.tsx create mode 100644 client/src/components/combined/MunicipalityContext.tsx create mode 100644 client/src/components/combined/OverviewPanel.tsx rename client/src/components/vehicles/{VehicleMap.tsx => VehicleLayer.tsx} (66%) rename client/src/components/watercraft/{WatercraftMap.tsx => WatercraftLayer.tsx} (83%) create mode 100644 client/src/map/MapHost.tsx create mode 100644 client/src/map/geometry.ts create mode 100644 client/src/map/mapContext.ts create mode 100644 client/src/map/useYearPlayback.ts create mode 100644 client/src/pages/ThurgauCombinedPage.tsx create mode 100644 client/src/traffic/useTrafficData.ts create mode 100644 client/src/vehicles/useVehicleData.ts create mode 100644 client/src/watercraft/useWatercraftData.ts diff --git a/CLAUDE.md b/CLAUDE.md index f2ee12b..a374fd9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,11 +105,13 @@ Brand counts only include the group `Personenwagen`, with `Andere` always last. ### Client -- Routing with `react-router-dom`: `/` is the start page (`pages/HomePage.tsx`) with one large tile per map, each map has its own page (`/verkehr/thurgau` → `pages/TrafficThurgauPage.tsx`, `/schifffahrt/thurgau?jahr=2023` → `pages/WatercraftThurgauPage.tsx`, `/fahrzeuge/thurgau?jahr=2025` → `pages/VehiclesThurgauPage.tsx`). Tiles come from the registry in `src/maps.ts`; a new map needs an entry there (with a preview image in `public/previews/`) and a route in `App.tsx`. Deep links work because the server falls back to `index.html`. +- Routing with `react-router-dom`: `/` is the start page (`pages/HomePage.tsx`) with one large tile per entry in `src/maps.ts`. Only the combined map has a tile; the single maps are reached through the "Einzelkarte" links in its layer cards. Each map has its own page (`/verkehr/thurgau` → `pages/TrafficThurgauPage.tsx`, `/schifffahrt/thurgau?jahr=2023` → `pages/WatercraftThurgauPage.tsx`, `/fahrzeuge/thurgau?jahr=2025` → `pages/VehiclesThurgauPage.tsx`, `/karte/thurgau?ebenen=fahrzeuge,boote,verkehr&jahr=2025` → `pages/ThurgauCombinedPage.tsx`). A new map needs a route in `App.tsx` and a layer card on the combined page; only a new standalone map needs an entry in `src/maps.ts` (with a preview image in `public/previews/`). Deep links work because the server falls back to `index.html`. +- `map/MapHost.tsx` owns the single Leaflet map (base layers, resize, the `odv-areas` pane at z-index 350 below the default overlay pane) and provides it via `map/mapContext.ts` (`useMap`, `useMapAttribution`). Each dataset is a layer component that renders `null` and attaches to that map: `components/TrafficLayer.tsx`, `components/watercraft/WatercraftLayer.tsx`, `components/vehicles/VehicleLayer.tsx`. Layers add their data credit to the attribution control themselves and remove everything they added on unmount, so several can share one map. Data loading and per-dataset UI state live in hooks (`traffic/useTrafficData.ts`, `watercraft/useWatercraftData.ts`, `vehicles/useVehicleData.ts`, plus `map/useYearPlayback.ts` for the `jahr` param and year playback), used by both the single pages and the combined page. +- Combined page: one `MapHost` with the three layers toggled from `components/combined/LayerPanel.tsx` / `LayerCard.tsx`; the year list is the union of the active yearly layers. The side panel shows the selected municipality, location or station, otherwise `OverviewPanel`. The municipality panel adds `MunicipalityContext` (stations and harbours assigned with `map/geometry.ts` `assignToOutlines`). - `traffic/flowAnimator.ts` owns the animation clock (time of day in hours, play/pause, speed) and draws on a canvas above Leaflet's overlay pane. Dots spawn per direction at a rate proportional to the interpolated hourly count, colored and sized by vehicle group, offset to the right of the driving direction. It reports the time to React at ~10 Hz via `onTick`; React components only get the integer hour, so markers and charts don't re-render every frame. - The vehicle class order in `traffic/vehicleClasses.ts` must match the `VehicleClass` enum / `VehicleCounts.ToArray()` order; count arrays in the API are positional. -- Watercraft page: `components/watercraft/WatercraftMap.tsx` draws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS. `watercraft/categories.ts` folds categories into at most six coloured groups plus grey `Übrige` and grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years. -- Vehicle page: `components/vehicles/VehicleMap.tsx` draws a choropleth of the municipality outlines (polygons created once, restyled in place). `vehicles/metrics.ts` defines the metric (vehicles per 1000 inhabitants for all or one group, or a brand's share of passenger cars) and a 7-class quantile scale computed over all years, so colours stay comparable while playing through the years. `YearControls` is shared with the watercraft page. +- Watercraft page: `components/watercraft/WatercraftLayer.tsx` draws one SVG donut per location (area ∝ boats, segments by the selected dimension); markers are created once and resized in place, so year changes animate via CSS. `watercraft/categories.ts` folds categories into at most six coloured groups plus grey `Übrige` and grey "absent" groups; legend chips hide groups, which shrinks the donuts. The panel shows the canton or the selected location for the selected year plus a stacked trend over all years. +- Vehicle page: `components/vehicles/VehicleLayer.tsx` draws a choropleth of the municipality outlines (polygons created once, restyled in place). `vehicles/metrics.ts` defines the metric (vehicles per 1000 inhabitants for all or one group, or a brand's share of passenger cars) and a 7-class quantile scale computed over all years, so colours stay comparable while playing through the years. `YearControls` is shared with the watercraft page. - UI language is German (de-CH). Base maps (shared in `map/baseLayers.ts`) are swisstopo WMTS layers (grey `pixelkarte-grau` as default, colour `pixelkarte-farbe`, aerial `swissimage`), switchable via Leaflet's layer control; the choice is stored in localStorage (`odv.baseMap`). ## Conventions diff --git a/client/public/previews/combined-thurgau.svg b/client/public/previews/combined-thurgau.svg new file mode 100644 index 0000000..084cd55 --- /dev/null +++ b/client/public/previews/combined-thurgau.svg @@ -0,0 +1,62 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Ebenen + + Fahrzeugbestand + + Wasserfahrzeuge + + Strassenverkehr + + diff --git a/client/public/previews/traffic-thurgau.svg b/client/public/previews/traffic-thurgau.svg deleted file mode 100644 index 24234f3..0000000 --- a/client/public/previews/traffic-thurgau.svg +++ /dev/null @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/public/previews/vehicles-thurgau.svg b/client/public/previews/vehicles-thurgau.svg deleted file mode 100644 index 08e61c7..0000000 --- a/client/public/previews/vehicles-thurgau.svg +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/client/public/previews/watercraft-thurgau.svg b/client/public/previews/watercraft-thurgau.svg deleted file mode 100644 index 128f954..0000000 --- a/client/public/previews/watercraft-thurgau.svg +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 2021 - 2022 - 2023 - 2024 - 2025 - - - diff --git a/client/src/App.tsx b/client/src/App.tsx index 1d7e00a..877642d 100644 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,6 @@ import { Navigate, Route, Routes } from 'react-router-dom'; import { HomePage } from './pages/HomePage'; +import { ThurgauCombinedPage } from './pages/ThurgauCombinedPage'; import { TrafficThurgauPage } from './pages/TrafficThurgauPage'; import { VehiclesThurgauPage } from './pages/VehiclesThurgauPage'; import { WatercraftThurgauPage } from './pages/WatercraftThurgauPage'; @@ -11,6 +12,7 @@ export function App() { } /> } /> } /> + } /> } /> ); diff --git a/client/src/components/TrafficMap.tsx b/client/src/components/TrafficLayer.tsx similarity index 77% rename from client/src/components/TrafficMap.tsx rename to client/src/components/TrafficLayer.tsx index cd1da30..a50ef97 100644 --- a/client/src/components/TrafficMap.tsx +++ b/client/src/components/TrafficLayer.tsx @@ -1,80 +1,72 @@ -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 { escapeHtml } from '../map/baseLayers'; +import { useMap, useMapAttribution } from '../map/mapContext'; import { FlowAnimator } from '../traffic/flowAnimator'; import { sumCounts } from '../traffic/vehicleClasses'; -interface TrafficMapProps { +interface TrafficLayerProps { stations: Station[]; day: DayView | null; hour: number; selectedCode: number | null; onSelect: (code: number) => void; onAnimatorReady: (animator: FlowAnimator) => void; + fitToData?: boolean; } -const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1]; const DATA_ATTRIBUTION = - 'Kanton Thurgau'; + 'Verkehr: Kanton Thurgau'; -export function TrafficMap({ +export function TrafficLayer({ stations, day, hour, selectedCode, onSelect, onAnimatorReady, -}: TrafficMapProps) { - const containerRef = useRef(null); - const mapRef = useRef(null); + fitToData = true, +}: TrafficLayerProps) { + const map = useMap(); + useMapAttribution(DATA_ATTRIBUTION); const animatorRef = useRef(null); const roadsRef = useRef(null); const markersRef = useRef>(new Map()); const onSelectRef = useRef(onSelect); onSelectRef.current = onSelect; - const fittedRef = useRef(false); + const fittedRef = useRef(!fitToData); 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 roads = L.layerGroup().addTo(map); const animator = new FlowAnimator(map, canvas); animator.start(); - mapRef.current = map; + roadsRef.current = roads; animatorRef.current = animator; onAnimatorReady(animator); - - const resizeObserver = new ResizeObserver(() => map.invalidateSize()); - resizeObserver.observe(containerRef.current); + const markers = markersRef.current; return () => { - resizeObserver.disconnect(); animator.dispose(); - map.remove(); - mapRef.current = null; + canvas.remove(); + roads.remove(); + markers.forEach((marker) => marker.remove()); + markers.clear(); + roadsRef.current = null; animatorRef.current = null; - markersRef.current.clear(); }; - }, [onAnimatorReady]); + }, [map, onAnimatorReady]); useEffect(() => { - const map = mapRef.current; const roads = roadsRef.current; - if (!map || !roads) { + if (!roads) { return; } @@ -120,7 +112,7 @@ export function TrafficMap({ padding: [40, 40], }); } - }, [stations]); + }, [map, stations]); useEffect(() => { animatorRef.current?.setDay(day); @@ -159,7 +151,7 @@ export function TrafficMap({ { direction: 'top', offset: [0, -6] }, ); } - }, [stations, day, hour, selectedCode]); + }, [map, stations, day, hour, selectedCode]); - return
; + return null; } diff --git a/client/src/components/combined/LayerCard.tsx b/client/src/components/combined/LayerCard.tsx new file mode 100644 index 0000000..199bd3b --- /dev/null +++ b/client/src/components/combined/LayerCard.tsx @@ -0,0 +1,44 @@ +import type { ReactNode } from 'react'; +import { Link } from 'react-router-dom'; + +interface LayerCardProps { + title: string; + subtitle: string; + color: string; + active: boolean; + detailPath: string; + note?: string | null; + onToggle: () => void; + children?: ReactNode; +} + +export function LayerCard({ + title, + subtitle, + color, + active, + detailPath, + note, + onToggle, + children, +}: LayerCardProps) { + return ( +
+
+ + + Einzelkarte + +
+ {active && note &&

{note}

} + {active && children &&
{children}
} +
+ ); +} diff --git a/client/src/components/combined/LayerPanel.tsx b/client/src/components/combined/LayerPanel.tsx new file mode 100644 index 0000000..b47dffa --- /dev/null +++ b/client/src/components/combined/LayerPanel.tsx @@ -0,0 +1,21 @@ +import { useState, type ReactNode } from 'react'; + +const WIDE_SCREEN = '(min-width: 901px)'; + +export function LayerPanel({ children }: { children: ReactNode }) { + const [open, setOpen] = useState(() => window.matchMedia(WIDE_SCREEN).matches); + + return ( +
+ + {open &&
{children}
} +
+ ); +} diff --git a/client/src/components/combined/MunicipalityContext.tsx b/client/src/components/combined/MunicipalityContext.tsx new file mode 100644 index 0000000..9cf52e9 --- /dev/null +++ b/client/src/components/combined/MunicipalityContext.tsx @@ -0,0 +1,81 @@ +import type { DayView, Station } from '../../api/traffic'; +import type { LocationSummary } from '../../api/watercraft'; +import { formatNumber } from '../../traffic/format'; +import { sumCounts } from '../../traffic/vehicleClasses'; + +interface MunicipalityContextProps { + stations: Station[] | null; + locations: LocationSummary[] | null; + day: DayView | null; + hour: number; + year: number; + onSelectStation: (code: number) => void; + onSelectLocation: (name: string) => void; +} + +export function MunicipalityContext({ + stations, + locations, + day, + hour, + year, + onSelectStation, + onSelectLocation, +}: MunicipalityContextProps) { + if (!stations && !locations) { + return null; + } + + const dayByStation = new Map(day?.stations.map((s) => [s.code, s]) ?? []); + const hourLabel = `${String(hour).padStart(2, '0')}:00`; + + return ( +
+

In dieser Gemeinde

+ + {stations && + (stations.length > 0 ? ( +
    + {stations.map((station) => { + const total = + dayByStation + .get(station.code) + ?.directions.reduce((sum, d) => sum + sumCounts(d.hours[hour]), 0) ?? 0; + return ( +
  • + +
  • + ); + })} +
+ ) : ( +

Keine Verkehrszählstelle.

+ ))} + + {locations && + (locations.length > 0 ? ( +
    + {locations.map((location) => ( +
  • + +
  • + ))} +
+ ) : ( +

Kein Bootsstandort.

+ ))} +
+ ); +} diff --git a/client/src/components/combined/OverviewPanel.tsx b/client/src/components/combined/OverviewPanel.tsx new file mode 100644 index 0000000..2edbe8a --- /dev/null +++ b/client/src/components/combined/OverviewPanel.tsx @@ -0,0 +1,119 @@ +import type { VehicleMeta, VehicleYearView } from '../../api/vehicles'; +import type { YearView } from '../../api/watercraft'; +import { formatDate, formatNumber } from '../../traffic/format'; +import { metricValue } from '../../vehicles/metrics'; + +interface OverviewPanelProps { + year: number | null; + vehicles: { meta: VehicleMeta; view: VehicleYearView | null; firstYear: number } | null; + watercraft: { view: YearView | null; firstYear: number } | null; + traffic: { + stationCount: number; + date: string | null; + hour: number; + hourTotal: number; + firstDate: string | null; + } | null; +} + +export function OverviewPanel({ year, vehicles, watercraft, traffic }: OverviewPanelProps) { + const carIndex = vehicles?.meta.groups.indexOf('Personenwagen') ?? -1; + const carDensity = + vehicles?.view && carIndex >= 0 + ? metricValue(vehicles.view.canton, { kind: 'density', group: carIndex }) + : null; + + return ( + + ); +} diff --git a/client/src/components/vehicles/MunicipalityPanel.tsx b/client/src/components/vehicles/MunicipalityPanel.tsx index 0538952..68635ff 100644 --- a/client/src/components/vehicles/MunicipalityPanel.tsx +++ b/client/src/components/vehicles/MunicipalityPanel.tsx @@ -7,6 +7,7 @@ import { Tooltip, type ChartOptions, } from 'chart.js'; +import type { ReactNode } from 'react'; import { Bar } from 'react-chartjs-2'; import type { AreaSummary, VehicleMeta, VehicleYearView } from '../../api/vehicles'; import { formatDate, formatNumber } from '../../traffic/format'; @@ -36,6 +37,7 @@ interface MunicipalityPanelProps { metric: Metric; metricTitle: string; onClose: () => void; + children?: ReactNode; } function findArea(view: VehicleYearView | undefined, id: string | null): AreaSummary | null { @@ -53,6 +55,7 @@ export function MunicipalityPanel({ metric, metricTitle, onClose, + children, }: MunicipalityPanelProps) { const yearIndex = years.findIndex((y) => y.year === year); const view = years[yearIndex]; @@ -310,6 +313,8 @@ export function MunicipalityPanel({ />
+ + {children} ); } diff --git a/client/src/components/vehicles/VehicleMap.tsx b/client/src/components/vehicles/VehicleLayer.tsx similarity index 66% rename from client/src/components/vehicles/VehicleMap.tsx rename to client/src/components/vehicles/VehicleLayer.tsx index 5a4a8ea..c13c335 100644 --- a/client/src/components/vehicles/VehicleMap.tsx +++ b/client/src/components/vehicles/VehicleLayer.tsx @@ -1,8 +1,8 @@ -import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; import { useEffect, useRef } from 'react'; import type { AreaSummary, MunicipalityShape } from '../../api/vehicles'; -import { addSwisstopoBaseLayers, escapeHtml } from '../../map/baseLayers'; +import { escapeHtml } from '../../map/baseLayers'; +import { AREA_PANE, useMap, useMapAttribution } from '../../map/mapContext'; import { formatNumber } from '../../traffic/format'; import { formatMetric, @@ -13,7 +13,7 @@ import { type Metric, } from '../../vehicles/metrics'; -interface VehicleMapProps { +interface VehicleLayerProps { shapes: MunicipalityShape[]; areas: AreaSummary[]; metric: Metric; @@ -21,16 +21,17 @@ interface VehicleMapProps { scale: ColorScale; selectedId: string | null; onSelect: (id: string) => void; + fillOpacity?: number; + fitToData?: boolean; } -const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1]; const DATA_ATTRIBUTION = - 'Strassenverkehrsamt Thurgau, ' + + 'Fahrzeuge: Strassenverkehrsamt Thurgau, ' + 'swissBOUNDARIES3D'; const BORDER_COLOR = '#ffffff'; const SELECTED_BORDER_COLOR = '#0f172a'; -export function VehicleMap({ +export function VehicleLayer({ shapes, areas, metric, @@ -38,37 +39,28 @@ export function VehicleMap({ scale, selectedId, onSelect, -}: VehicleMapProps) { - const containerRef = useRef(null); - const mapRef = useRef(null); + fillOpacity = 0.78, + fitToData = true, +}: VehicleLayerProps) { + const map = useMap(); + useMapAttribution(DATA_ATTRIBUTION); const layersRef = useRef>(new Map()); const onSelectRef = useRef(onSelect); onSelectRef.current = onSelect; + const fillOpacityRef = useRef(fillOpacity); + fillOpacityRef.current = fillOpacity; + const fitToDataRef = useRef(fitToData); useEffect(() => { - if (!containerRef.current) { - return; - } - - const map = L.map(containerRef.current, { zoomSnap: 0.5 }).setView(THURGAU_CENTER, 10); - addSwisstopoBaseLayers(map, DATA_ATTRIBUTION); - mapRef.current = map; - - const resizeObserver = new ResizeObserver(() => map.invalidateSize()); - resizeObserver.observe(containerRef.current); const layers = layersRef.current; - return () => { - resizeObserver.disconnect(); - map.remove(); - mapRef.current = null; + layers.forEach((layer) => layer.remove()); layers.clear(); }; - }, []); + }, [map]); useEffect(() => { - const map = mapRef.current; - if (!map || shapes.length === 0 || layersRef.current.size > 0) { + if (shapes.length === 0 || layersRef.current.size > 0) { return; } @@ -77,22 +69,27 @@ export function VehicleMap({ polygon.map((ring) => ring.map(([lon, lat]) => [lat, lon] as L.LatLngTuple)), ); const layer = L.polygon(latLngs, { + pane: AREA_PANE, color: BORDER_COLOR, weight: 1, - fillOpacity: 0.78, + fillOpacity: fillOpacityRef.current, smoothFactor: 0.5, }) .on('click', () => onSelectRef.current(shape.id)) - .on('mouseover', () => layer.setStyle({ fillOpacity: 0.95 })) - .on('mouseout', () => layer.setStyle({ fillOpacity: 0.78 })) + .on('mouseover', () => + layer.setStyle({ fillOpacity: Math.min(1, fillOpacityRef.current + 0.17) }), + ) + .on('mouseout', () => layer.setStyle({ fillOpacity: fillOpacityRef.current })) .addTo(map); layersRef.current.set(shape.id, layer); } - const bounds = L.latLngBounds([]); - layersRef.current.forEach((layer) => bounds.extend(layer.getBounds())); - map.fitBounds(bounds, { paddingTopLeft: [20, 20], paddingBottomRight: [20, 150] }); - }, [shapes]); + if (fitToDataRef.current) { + const bounds = L.latLngBounds([]); + layersRef.current.forEach((layer) => bounds.extend(layer.getBounds())); + map.fitBounds(bounds, { paddingTopLeft: [20, 20], paddingBottomRight: [20, 150] }); + } + }, [map, shapes]); useEffect(() => { const byId = new Map(areas.map((area) => [area.id, area])); @@ -102,6 +99,7 @@ export function VehicleMap({ const selected = id === selectedId; layer.setStyle({ fillColor: scaleColor(scale, value), + fillOpacity, color: selected ? SELECTED_BORDER_COLOR : BORDER_COLOR, weight: selected ? 3 : 1, }); @@ -115,9 +113,9 @@ export function VehicleMap({ offset: [0, -8], }); }); - }, [areas, metric, metricTitle, scale, selectedId, shapes]); + }, [map, areas, metric, metricTitle, scale, selectedId, shapes, fillOpacity]); - return
; + return null; } function tooltipHtml( diff --git a/client/src/components/watercraft/WatercraftMap.tsx b/client/src/components/watercraft/WatercraftLayer.tsx similarity index 83% rename from client/src/components/watercraft/WatercraftMap.tsx rename to client/src/components/watercraft/WatercraftLayer.tsx index c2b1b18..761222c 100644 --- a/client/src/components/watercraft/WatercraftMap.tsx +++ b/client/src/components/watercraft/WatercraftLayer.tsx @@ -1,67 +1,54 @@ -import 'leaflet/dist/leaflet.css'; import L from 'leaflet'; import { useEffect, useRef } from 'react'; import type { Dimension, LocationSummary } from '../../api/watercraft'; -import { addSwisstopoBaseLayers, escapeHtml } from '../../map/baseLayers'; +import { escapeHtml } from '../../map/baseLayers'; +import { useMap, useMapAttribution } from '../../map/mapContext'; import { formatNumber } from '../../traffic/format'; import { groupCounts, type CategoryGroup } from '../../watercraft/categories'; -interface WatercraftMapProps { +interface WatercraftLayerProps { locations: LocationSummary[]; dimension: Dimension | null; groups: CategoryGroup[]; hidden: Set; selectedName: string | null; onSelect: (name: string) => void; + fitToData?: boolean; } -const THURGAU_LAKE_CENTER: L.LatLngTuple = [47.6, 9.1]; const DATA_ATTRIBUTION = - 'Kantonspolizei Thurgau'; + 'Boote: Kantonspolizei Thurgau'; export function markerRadius(count: number): number { return count <= 0 ? 4 : 5 + Math.sqrt(count) * 0.95; } -export function WatercraftMap({ +export function WatercraftLayer({ locations, dimension, groups, hidden, selectedName, onSelect, -}: WatercraftMapProps) { - const containerRef = useRef(null); - const mapRef = useRef(null); + fitToData = true, +}: WatercraftLayerProps) { + const map = useMap(); + useMapAttribution(DATA_ATTRIBUTION); const markersRef = useRef>(new Map()); const onSelectRef = useRef(onSelect); onSelectRef.current = onSelect; - const fittedRef = useRef(false); + const fittedRef = useRef(!fitToData); useEffect(() => { - if (!containerRef.current) { - return; - } - - const map = L.map(containerRef.current, { zoomSnap: 0.5 }).setView(THURGAU_LAKE_CENTER, 10); - addSwisstopoBaseLayers(map, DATA_ATTRIBUTION); - mapRef.current = map; - - const resizeObserver = new ResizeObserver(() => map.invalidateSize()); - resizeObserver.observe(containerRef.current); const markers = markersRef.current; - return () => { - resizeObserver.disconnect(); - map.remove(); - mapRef.current = null; + markers.forEach((marker) => marker.remove()); markers.clear(); }; - }, []); + }, [map]); useEffect(() => { - const map = mapRef.current; - if (!map || !dimension) { + if (!dimension) { return; } @@ -117,9 +104,9 @@ export function WatercraftMap({ padding: [50, 50], }); } - }, [locations, dimension, groups, hidden, selectedName]); + }, [map, locations, dimension, groups, hidden, selectedName]); - return
; + return null; } function donutSvg( diff --git a/client/src/map/MapHost.tsx b/client/src/map/MapHost.tsx new file mode 100644 index 0000000..19ffeda --- /dev/null +++ b/client/src/map/MapHost.tsx @@ -0,0 +1,48 @@ +import 'leaflet/dist/leaflet.css'; +import L from 'leaflet'; +import { useEffect, useRef, useState, type ReactNode } from 'react'; +import { addSwisstopoBaseLayers } from './baseLayers'; +import { AREA_PANE, MapContext } from './mapContext'; + +interface MapHostProps { + center: L.LatLngTuple; + zoom?: number; + children?: ReactNode; +} + +export function MapHost({ center, zoom = 10, children }: MapHostProps) { + const containerRef = useRef(null); + const initialViewRef = useRef({ center, zoom }); + const [map, setMap] = useState(null); + + useEffect(() => { + const container = containerRef.current; + if (!container) { + return; + } + + const created = L.map(container, { zoomSnap: 0.5 }).setView( + initialViewRef.current.center, + initialViewRef.current.zoom, + ); + created.createPane(AREA_PANE).style.zIndex = '350'; + addSwisstopoBaseLayers(created); + + const resizeObserver = new ResizeObserver(() => created.invalidateSize()); + resizeObserver.observe(container); + setMap(created); + + return () => { + resizeObserver.disconnect(); + setMap(null); + created.remove(); + }; + }, []); + + return ( + <> +
+ {map && {children}} + + ); +} diff --git a/client/src/map/baseLayers.ts b/client/src/map/baseLayers.ts index 996e324..db08ea6 100644 --- a/client/src/map/baseLayers.ts +++ b/client/src/map/baseLayers.ts @@ -1,5 +1,8 @@ import L from 'leaflet'; +export const THURGAU_CENTER: L.LatLngTuple = [47.57, 9.1]; +export const THURGAU_LAKE_CENTER: L.LatLngTuple = [47.6, 9.1]; + const BASE_MAP_STORAGE_KEY = 'odv.baseMap'; const BASE_MAPS = [ @@ -8,8 +11,8 @@ const BASE_MAPS = [ { name: 'Luftbild', layer: 'ch.swisstopo.swissimage', maxNativeZoom: 19 }, ]; -export function addSwisstopoBaseLayers(map: L.Map, dataAttribution: string): void { - const attribution = `© swisstopo · Daten: ${dataAttribution}`; +export function addSwisstopoBaseLayers(map: L.Map): void { + const attribution = '© swisstopo'; const baseLayers: Record = Object.fromEntries( BASE_MAPS.map((baseMap) => [ baseMap.name, diff --git a/client/src/map/geometry.ts b/client/src/map/geometry.ts new file mode 100644 index 0000000..08a9101 --- /dev/null +++ b/client/src/map/geometry.ts @@ -0,0 +1,88 @@ +const METERS_PER_DEGREE_LAT = 110_540; +const METERS_PER_DEGREE_LON_AT_EQUATOR = 111_320; + +export interface Outline { + id: string; + polygons: number[][][][]; +} + +export function containsPoint(polygons: number[][][][], lon: number, lat: number): boolean { + return polygons.some( + ([outer, ...holes]) => + !!outer && insideRing(outer, lon, lat) && !holes.some((hole) => insideRing(hole, lon, lat)), + ); +} + +export function distanceToOutline(polygons: number[][][][], lon: number, lat: number): number { + if (containsPoint(polygons, lon, lat)) { + return 0; + } + const kx = METERS_PER_DEGREE_LON_AT_EQUATOR * Math.cos((lat * Math.PI) / 180); + const ky = METERS_PER_DEGREE_LAT; + let best = Infinity; + for (const polygon of polygons) { + for (const ring of polygon) { + for (let i = 1; i < ring.length; i++) { + const ax = (ring[i - 1][0] - lon) * kx; + const ay = (ring[i - 1][1] - lat) * ky; + const bx = (ring[i][0] - lon) * kx; + const by = (ring[i][1] - lat) * ky; + best = Math.min(best, distanceToSegment(ax, ay, bx, by)); + } + } + } + return best; +} + +export function assignToOutlines( + outlines: Outline[], + items: T[], + position: (item: T) => [number, number] | null, + maxDistanceMeters: number, +): Map { + const result = new Map(); + for (const item of items) { + const point = position(item); + if (!point) { + continue; + } + const [lon, lat] = point; + let bestId: string | null = null; + let bestDistance = maxDistanceMeters; + for (const outline of outlines) { + const distance = distanceToOutline(outline.polygons, lon, lat); + if (distance <= bestDistance) { + bestId = outline.id; + bestDistance = distance; + if (distance === 0) { + break; + } + } + } + if (bestId !== null) { + result.set(bestId, [...(result.get(bestId) ?? []), item]); + } + } + return result; +} + +function insideRing(ring: number[][], x: number, y: number): boolean { + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, yi] = ring[i]; + const [xj, yj] = ring[j]; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) { + inside = !inside; + } + } + return inside; +} + +function distanceToSegment(ax: number, ay: number, bx: number, by: number): number { + const dx = bx - ax; + const dy = by - ay; + const lengthSquared = dx * dx + dy * dy; + const t = + lengthSquared === 0 ? 0 : Math.max(0, Math.min(1, -(ax * dx + ay * dy) / lengthSquared)); + return Math.hypot(ax + t * dx, ay + t * dy); +} diff --git a/client/src/map/mapContext.ts b/client/src/map/mapContext.ts new file mode 100644 index 0000000..6d9f229 --- /dev/null +++ b/client/src/map/mapContext.ts @@ -0,0 +1,24 @@ +import type L from 'leaflet'; +import { createContext, useContext, useEffect } from 'react'; + +export const AREA_PANE = 'odv-areas'; + +export const MapContext = createContext(null); + +export function useMap(): L.Map { + const map = useContext(MapContext); + if (!map) { + throw new Error('useMap must be used inside a MapHost'); + } + return map; +} + +export function useMapAttribution(attribution: string): void { + const map = useMap(); + useEffect(() => { + map.attributionControl.addAttribution(attribution); + return () => { + map.attributionControl.removeAttribution(attribution); + }; + }, [map, attribution]); +} diff --git a/client/src/map/useYearPlayback.ts b/client/src/map/useYearPlayback.ts new file mode 100644 index 0000000..8dc2415 --- /dev/null +++ b/client/src/map/useYearPlayback.ts @@ -0,0 +1,45 @@ +import { useCallback, useEffect, useState } from 'react'; +import { useSearchParams } from 'react-router-dom'; + +const PLAY_INTERVAL_MS = 1600; +const YEAR_PARAM = 'jahr'; + +export interface YearPlayback { + year: number | null; + setYear: (year: number) => void; + playing: boolean; + setPlaying: (playing: boolean) => void; +} + +export function useYearPlayback(years: number[]): YearPlayback { + const [searchParams, setSearchParams] = useSearchParams(); + const [playing, setPlaying] = useState(false); + + const requested = Number(searchParams.get(YEAR_PARAM)); + const year = years.includes(requested) ? requested : (years[years.length - 1] ?? null); + + const setYear = useCallback( + (value: number) => + setSearchParams( + (params) => { + params.set(YEAR_PARAM, String(value)); + return params; + }, + { replace: true }, + ), + [setSearchParams], + ); + + useEffect(() => { + if (!playing || years.length < 2 || year === null) { + return; + } + const timer = window.setTimeout(() => { + const index = years.indexOf(year); + setYear(years[(index + 1) % years.length]); + }, PLAY_INTERVAL_MS); + return () => window.clearTimeout(timer); + }, [playing, years, year, setYear]); + + return { year, setYear, playing, setPlaying }; +} diff --git a/client/src/maps.ts b/client/src/maps.ts index f203417..d2dfc49 100644 --- a/client/src/maps.ts +++ b/client/src/maps.ts @@ -10,33 +10,13 @@ export interface MapEntry { export const MAPS: MapEntry[] = [ { - path: '/verkehr/thurgau', - title: 'Strassenverkehr', + path: '/karte/thurgau', + title: 'Alle Daten auf einer Karte', region: 'Kanton Thurgau', description: - 'Fahrzeuge fahren animiert über die Strassen der 64 Zählstellen – stündlich nach Fahrzeugklasse, mit Tagesverlauf und Auswertungen pro Zählstelle.', - source: 'Tiefbauamt Kanton Thurgau', - tags: ['Verkehr', 'Stundenwerte', 'Animation'], - preview: '/previews/traffic-thurgau.svg', - }, - { - path: '/schifffahrt/thurgau', - title: 'Wasserfahrzeuge', - region: 'Kanton Thurgau', - description: - 'Alle immatrikulierten Boote an Bodensee, Untersee und Rhein – pro Standort nach Schiffsart, Antrieb, Treibstoff oder Abgasnorm, mit Jahresvergleich seit 2021.', - source: 'Kantonspolizei Thurgau, Schifffahrtskontrolle', - tags: ['Schifffahrt', 'Jahresbestand', 'Standorte'], - preview: '/previews/watercraft-thurgau.svg', - }, - { - path: '/fahrzeuge/thurgau', - title: 'Fahrzeugbestand', - region: 'Kanton Thurgau', - description: - 'Alle eingelösten Strassenfahrzeuge der 80 Gemeinden – Fahrzeugdichte pro Einwohner nach Fahrzeuggruppe oder Anteil einer Automarke, mit Jahresvergleich seit 2023.', - source: 'Strassenverkehrsamt Kanton Thurgau', - tags: ['Fahrzeuge', 'Gemeinden', 'Automarken'], - preview: '/previews/vehicles-thurgau.svg', + 'Fahrzeugbestand, Wasserfahrzeuge und Strassenverkehr als Ebenen übereinander – einzeln ein- und ausschaltbar, mit Zählstellen und Bootsstandorten pro Gemeinde.', + source: 'Kanton Thurgau, data.tg.ch', + tags: ['Ebenen', 'Gemeinden', 'Kombiniert'], + preview: '/previews/combined-thurgau.svg', }, ]; diff --git a/client/src/pages/ThurgauCombinedPage.tsx b/client/src/pages/ThurgauCombinedPage.tsx new file mode 100644 index 0000000..1640a24 --- /dev/null +++ b/client/src/pages/ThurgauCombinedPage.tsx @@ -0,0 +1,476 @@ +import { memo, useCallback, useEffect, useMemo, useState, type ReactNode } from 'react'; +import { Link, useSearchParams } from 'react-router-dom'; +import { LayerCard } from '../components/combined/LayerCard'; +import { LayerPanel } from '../components/combined/LayerPanel'; +import { MunicipalityContext } from '../components/combined/MunicipalityContext'; +import { OverviewPanel } from '../components/combined/OverviewPanel'; +import { DatasetCredit, LicenseLink } from '../components/DatasetCredit'; +import { Legend } from '../components/Legend'; +import { StationPanel } from '../components/StationPanel'; +import { TimeControls } from '../components/TimeControls'; +import { TrafficLayer } from '../components/TrafficLayer'; +import { MetricControls } from '../components/vehicles/MetricControls'; +import { MunicipalityPanel } from '../components/vehicles/MunicipalityPanel'; +import { VehicleLayer } from '../components/vehicles/VehicleLayer'; +import { CategoryLegend } from '../components/watercraft/CategoryLegend'; +import { LocationPanel } from '../components/watercraft/LocationPanel'; +import { WatercraftLayer } from '../components/watercraft/WatercraftLayer'; +import { YearControls } from '../components/watercraft/YearControls'; +import { THURGAU_CENTER } from '../map/baseLayers'; +import { assignToOutlines } from '../map/geometry'; +import { MapHost } from '../map/MapHost'; +import { useYearPlayback } from '../map/useYearPlayback'; +import { formatDate, formatNumber } from '../traffic/format'; +import { useTrafficData } from '../traffic/useTrafficData'; +import { useVehicleData } from '../vehicles/useVehicleData'; +import { useWatercraftData } from '../watercraft/useWatercraftData'; + +const MemoStationPanel = memo(StationPanel); +const MemoLocationPanel = memo(LocationPanel); +const MemoMunicipalityPanel = memo(MunicipalityPanel); + +type LayerKey = 'fahrzeuge' | 'boote' | 'verkehr'; + +type Selection = + | { layer: 'fahrzeuge'; id: string } + | { layer: 'boote'; name: string } + | { layer: 'verkehr'; code: number }; + +const LAYER_ORDER: LayerKey[] = ['fahrzeuge', 'boote', 'verkehr']; +const LAYER_PARAM = 'ebenen'; +const STATION_MAX_DISTANCE_M = 250; +const HARBOUR_MAX_DISTANCE_M = 1500; +const SHARED_FILL_OPACITY = 0.55; + +function parseLayers(value: string | null): Set { + if (value === null) { + return new Set(LAYER_ORDER); + } + return new Set(LAYER_ORDER.filter((key) => value.split(',').includes(key))); +} + +export function ThurgauCombinedPage() { + const [searchParams, setSearchParams] = useSearchParams(); + const layerParam = searchParams.get(LAYER_PARAM); + const active = useMemo(() => parseLayers(layerParam), [layerParam]); + const showVehicles = active.has('fahrzeuge'); + const showBoats = active.has('boote'); + const showTraffic = active.has('verkehr'); + + const toggleLayer = useCallback( + (key: LayerKey) => + setSearchParams( + (params) => { + const current = parseLayers(params.get(LAYER_PARAM)); + if (!current.delete(key)) { + current.add(key); + } + params.set(LAYER_PARAM, LAYER_ORDER.filter((k) => current.has(k)).join(',')); + return params; + }, + { replace: true }, + ), + [setSearchParams], + ); + + const traffic = useTrafficData(); + const watercraft = useWatercraftData(); + const vehicles = useVehicleData(); + + const yearList = useMemo(() => { + const all = new Set([ + ...(showVehicles ? vehicles.yearNumbers : []), + ...(showBoats ? watercraft.yearNumbers : []), + ]); + return [...all].sort((a, b) => a - b); + }, [showVehicles, showBoats, vehicles.yearNumbers, watercraft.yearNumbers]); + const { year, setYear, playing, setPlaying } = useYearPlayback(yearList); + const yearEntries = useMemo( + () => + yearList.map((y) => ({ + year: y, + referenceDate: + vehicles.years.find((v) => v.year === y)?.referenceDate ?? + watercraft.years.find((w) => w.year === y)?.referenceDate ?? + null, + })), + [yearList, vehicles.years, watercraft.years], + ); + + const vehicleView = vehicles.years.find((y) => y.year === year) ?? null; + const boatView = watercraft.years.find((y) => y.year === year) ?? null; + const boatLegendCounts = useMemo(() => watercraft.legendCounts(boatView), [watercraft, boatView]); + + const [selection, setSelection] = useState(null); + const visibleSelection = selection && active.has(selection.layer) ? selection : null; + + useEffect(() => { + document.title = 'Thurgau – alle Daten – OpenDataVisualizer'; + }, []); + + const selectMunicipality = useCallback( + (id: string) => + setSelection((current) => + current?.layer === 'fahrzeuge' && current.id === id ? null : { layer: 'fahrzeuge', id }, + ), + [], + ); + const selectLocation = useCallback( + (name: string) => + setSelection((current) => + current?.layer === 'boote' && current.name === name ? null : { layer: 'boote', name }, + ), + [], + ); + const selectStation = useCallback( + (code: number) => + setSelection((current) => + current?.layer === 'verkehr' && current.code === code ? null : { layer: 'verkehr', code }, + ), + [], + ); + const clearSelection = useCallback(() => setSelection(null), []); + + const outlines = vehicles.shapes; + const stationsByMunicipality = useMemo( + () => + assignToOutlines(outlines, traffic.stations, (s) => [s.lon, s.lat], STATION_MAX_DISTANCE_M), + [outlines, traffic.stations], + ); + const locationsByMunicipality = useMemo( + () => + assignToOutlines( + outlines, + boatView?.locations ?? [], + (l) => (l.lat !== null && l.lon !== null ? [l.lon, l.lat] : null), + HARBOUR_MAX_DISTANCE_M, + ), + [outlines, boatView], + ); + + const unplaced = boatView?.locations.filter((l) => l.lat === null) ?? []; + const selectedStation = + visibleSelection?.layer === 'verkehr' + ? (traffic.stations.find((s) => s.code === visibleSelection.code) ?? null) + : null; + + let panel: ReactNode; + if (visibleSelection?.layer === 'fahrzeuge' && vehicles.meta && year !== null) { + const id = visibleSelection.id; + panel = ( + + + + ); + } else if ( + visibleSelection?.layer === 'boote' && + watercraft.meta && + watercraft.dimension && + year !== null + ) { + panel = ( +