Add combined Thurgau map with switchable layers
- 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 <noreply@anthropic.com>
This commit is contained in:
parent
6a6b3a88c5
commit
39a1cd4009
29 changed files with 1655 additions and 604 deletions
|
|
@ -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
|
||||
|
|
|
|||
62
client/public/previews/combined-thurgau.svg
Normal file
62
client/public/previews/combined-thurgau.svg
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
|
||||
<defs>
|
||||
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#eef2ec"/>
|
||||
<stop offset="1" stop-color="#e3e8e1"/>
|
||||
</linearGradient>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
|
||||
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#0f172a" flood-opacity="0.25"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect width="800" height="450" fill="url(#land)"/>
|
||||
<path d="M380 0 L800 0 L800 150 C730 160 660 120 600 100 C540 80 470 60 380 0 Z" fill="#cfe0ee"/>
|
||||
<path d="M60 60 C120 50 200 70 260 66 C230 90 150 92 70 86 Z" fill="#cfe0ee"/>
|
||||
<g stroke="#ffffff" stroke-width="3" stroke-linejoin="round" opacity="0.75">
|
||||
<path d="M110 230 L170 168 L240 180 L262 250 L200 300 L130 288 Z" fill="#a4c6ea"/>
|
||||
<path d="M170 168 L230 110 L310 118 L322 176 L240 180 Z" fill="#73a6dd"/>
|
||||
<path d="M240 180 L322 176 L370 222 L340 290 L262 250 Z" fill="#4785cd"/>
|
||||
<path d="M130 288 L200 300 L262 250 L340 290 L310 352 L210 366 L150 336 Z" fill="#cfe0f4"/>
|
||||
<path d="M310 118 L400 100 L452 150 L420 210 L370 222 L322 176 Z" fill="#2763ad"/>
|
||||
<path d="M370 222 L420 210 L490 238 L470 310 L400 330 L340 290 Z" fill="#73a6dd"/>
|
||||
<path d="M310 352 L340 290 L400 330 L392 384 L330 396 Z" fill="#a4c6ea"/>
|
||||
<path d="M400 100 L480 80 L540 112 L520 176 L452 150 Z" fill="#4785cd"/>
|
||||
<path d="M452 150 L520 176 L560 220 L490 238 L420 210 Z" fill="#16447d"/>
|
||||
<path d="M490 238 L560 220 L620 258 L600 320 L530 330 L470 310 Z" fill="#a4c6ea"/>
|
||||
<path d="M540 112 L620 120 L660 170 L560 220 L520 176 Z" fill="#73a6dd"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#334155" stroke-width="6" stroke-linecap="round" opacity="0.35">
|
||||
<path d="M90 250 C180 230 260 215 360 200 S560 170 690 150"/>
|
||||
<path d="M330 400 C350 320 390 260 420 200 S470 110 500 70"/>
|
||||
</g>
|
||||
<g fill="#2a78d6">
|
||||
<circle cx="140" cy="243" r="4"/><circle cx="215" cy="228" r="4"/><circle cx="300" cy="210" r="4"/>
|
||||
<circle cx="392" cy="196" r="4"/><circle cx="470" cy="183" r="4"/><circle cx="560" cy="168" r="4"/>
|
||||
<circle cx="640" cy="156" r="4"/><circle cx="350" cy="340" r="4"/><circle cx="383" cy="275" r="4"/>
|
||||
<circle cx="447" cy="150" r="4"/><circle cx="480" cy="104" r="4"/>
|
||||
</g>
|
||||
<g fill="#eb6834">
|
||||
<circle cx="258" cy="222" r="5"/><circle cx="520" cy="176" r="5"/><circle cx="600" cy="162" r="5"/>
|
||||
</g>
|
||||
<g filter="url(#shadow)">
|
||||
<circle cx="470" cy="62" r="26" fill="#2a78d6"/>
|
||||
<path d="M470 36 A26 26 0 0 1 494 72 L470 62 Z" fill="#eb6834"/>
|
||||
<path d="M494 72 A26 26 0 0 1 452 81 L470 62 Z" fill="#11a37f"/>
|
||||
<circle cx="470" cy="62" r="13" fill="#ffffff"/>
|
||||
<circle cx="640" cy="118" r="20" fill="#2a78d6"/>
|
||||
<path d="M640 98 A20 20 0 0 1 659 124 L640 118 Z" fill="#eb6834"/>
|
||||
<circle cx="640" cy="118" r="10" fill="#ffffff"/>
|
||||
<circle cx="180" cy="74" r="15" fill="#11a37f"/>
|
||||
<path d="M180 59 A15 15 0 0 1 194 79 L180 74 Z" fill="#2a78d6"/>
|
||||
<circle cx="180" cy="74" r="7.5" fill="#ffffff"/>
|
||||
</g>
|
||||
<g filter="url(#shadow)">
|
||||
<rect x="24" y="300" width="190" height="126" rx="10" fill="#ffffff"/>
|
||||
<text x="40" y="326" font-family="system-ui, sans-serif" font-size="15" font-weight="600" fill="#0f172a">Ebenen</text>
|
||||
<rect x="40" y="342" width="14" height="14" rx="3" fill="#4785cd"/>
|
||||
<text x="64" y="354" font-family="system-ui, sans-serif" font-size="13" fill="#0f172a">Fahrzeugbestand</text>
|
||||
<rect x="40" y="368" width="14" height="14" rx="3" fill="#eb6834"/>
|
||||
<text x="64" y="380" font-family="system-ui, sans-serif" font-size="13" fill="#0f172a">Wasserfahrzeuge</text>
|
||||
<rect x="40" y="394" width="14" height="14" rx="3" fill="#334155"/>
|
||||
<text x="64" y="406" font-family="system-ui, sans-serif" font-size="13" fill="#0f172a">Strassenverkehr</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 3.8 KiB |
|
|
@ -1,74 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
|
||||
<defs>
|
||||
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#eef2ec"/>
|
||||
<stop offset="1" stop-color="#e3e8e1"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="450" fill="url(#land)"/>
|
||||
<path d="M520 0 C560 60 640 90 800 70 L800 0 Z" fill="#cfe0ee"/>
|
||||
<path d="M590 0 C610 30 660 45 720 40 C760 37 790 30 800 25 L800 0 Z" fill="#bcd4e8"/>
|
||||
<path d="M0 330 C120 300 210 330 300 300 C380 272 420 300 520 290" fill="none" stroke="#d6dcd3" stroke-width="10"/>
|
||||
<g fill="none" stroke="#9aa5b1" stroke-linecap="round">
|
||||
<path d="M-20 260 C120 250 220 210 330 220 C450 230 520 180 640 170 C720 163 780 150 820 140" stroke-width="14"/>
|
||||
<path d="M140 470 C170 380 230 300 330 220 C400 165 430 100 470 -20" stroke-width="12"/>
|
||||
<path d="M330 220 C380 270 470 330 620 360 C700 375 760 400 820 420" stroke-width="10"/>
|
||||
<path d="M640 170 C650 230 640 300 620 360" stroke-width="8"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#ffffff" stroke-width="1.5" stroke-dasharray="10 9" opacity="0.8">
|
||||
<path d="M-20 260 C120 250 220 210 330 220 C450 230 520 180 640 170 C720 163 780 150 820 140"/>
|
||||
<path d="M140 470 C170 380 230 300 330 220 C400 165 430 100 470 -20"/>
|
||||
</g>
|
||||
<g>
|
||||
<circle cx="40" cy="252" r="5" fill="#2563eb"/>
|
||||
<circle cx="78" cy="250" r="5" fill="#2563eb"/>
|
||||
<circle cx="105" cy="248" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="150" cy="242" r="5" fill="#2563eb"/>
|
||||
<circle cx="196" cy="230" r="7" fill="#ea580c"/>
|
||||
<circle cx="232" cy="219" r="5" fill="#2563eb"/>
|
||||
<circle cx="268" cy="213" r="5" fill="#2563eb"/>
|
||||
<circle cx="300" cy="212" r="5" fill="#0d9488"/>
|
||||
<circle cx="60" cy="266" r="5" fill="#2563eb"/>
|
||||
<circle cx="128" cy="261" r="5" fill="#2563eb"/>
|
||||
<circle cx="170" cy="252" r="5" fill="#2563eb"/>
|
||||
<circle cx="250" cy="231" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="290" cy="227" r="5" fill="#2563eb"/>
|
||||
<circle cx="372" cy="216" r="5" fill="#2563eb"/>
|
||||
<circle cx="420" cy="220" r="5" fill="#2563eb"/>
|
||||
<circle cx="470" cy="210" r="7" fill="#9333ea"/>
|
||||
<circle cx="520" cy="190" r="5" fill="#2563eb"/>
|
||||
<circle cx="566" cy="174" r="5" fill="#2563eb"/>
|
||||
<circle cx="612" cy="166" r="7" fill="#ea580c"/>
|
||||
<circle cx="690" cy="157" r="5" fill="#2563eb"/>
|
||||
<circle cx="740" cy="146" r="5" fill="#2563eb"/>
|
||||
<circle cx="398" cy="236" r="5" fill="#2563eb"/>
|
||||
<circle cx="448" cy="234" r="5" fill="#2563eb"/>
|
||||
<circle cx="545" cy="196" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="660" cy="180" r="5" fill="#2563eb"/>
|
||||
<circle cx="720" cy="168" r="5" fill="#2563eb"/>
|
||||
<circle cx="168" cy="420" r="5" fill="#2563eb"/>
|
||||
<circle cx="190" cy="370" r="5" fill="#2563eb"/>
|
||||
<circle cx="228" cy="320" r="7" fill="#ea580c"/>
|
||||
<circle cx="270" cy="280" r="5" fill="#2563eb"/>
|
||||
<circle cx="388" cy="166" r="5" fill="#2563eb"/>
|
||||
<circle cx="414" cy="124" r="5.5" fill="#16a34a"/>
|
||||
<circle cx="440" cy="66" r="5" fill="#2563eb"/>
|
||||
<circle cx="200" cy="400" r="5" fill="#2563eb"/>
|
||||
<circle cx="246" cy="318" r="5" fill="#2563eb"/>
|
||||
<circle cx="372" cy="196" r="5" fill="#2563eb"/>
|
||||
<circle cx="402" cy="146" r="5" fill="#2563eb"/>
|
||||
<circle cx="380" cy="268" r="5" fill="#2563eb"/>
|
||||
<circle cx="440" cy="306" r="5" fill="#2563eb"/>
|
||||
<circle cx="520" cy="338" r="7" fill="#ea580c"/>
|
||||
<circle cx="590" cy="350" r="5" fill="#2563eb"/>
|
||||
<circle cx="700" cy="384" r="5" fill="#2563eb"/>
|
||||
<circle cx="648" cy="230" r="5" fill="#2563eb"/>
|
||||
<circle cx="640" cy="300" r="5.5" fill="#16a34a"/>
|
||||
</g>
|
||||
<g fill="#ffffff" stroke="#0f172a" stroke-width="3">
|
||||
<circle cx="330" cy="220" r="14"/>
|
||||
<circle cx="640" cy="170" r="11"/>
|
||||
<circle cx="620" cy="360" r="9"/>
|
||||
<circle cx="96" cy="256" r="8"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.8 KiB |
|
|
@ -1,40 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
|
||||
<defs>
|
||||
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#eef2ec"/>
|
||||
<stop offset="1" stop-color="#e3e8e1"/>
|
||||
</linearGradient>
|
||||
<filter id="shadow" x="-10%" y="-10%" width="120%" height="120%">
|
||||
<feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#0f172a" flood-opacity="0.25"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect width="800" height="450" fill="url(#land)"/>
|
||||
<path d="M800 20 C730 50 680 80 640 96 C700 70 760 50 800 46 Z" fill="#cfe0ee"/>
|
||||
<g filter="url(#shadow)" stroke="#ffffff" stroke-width="3" stroke-linejoin="round">
|
||||
<path d="M110 230 L170 168 L240 180 L262 250 L200 300 L130 288 Z" fill="#a4c6ea"/>
|
||||
<path d="M170 168 L230 110 L310 118 L322 176 L240 180 Z" fill="#73a6dd"/>
|
||||
<path d="M240 180 L322 176 L370 222 L340 290 L262 250 Z" fill="#4785cd"/>
|
||||
<path d="M130 288 L200 300 L262 250 L340 290 L310 352 L210 366 L150 336 Z" fill="#cfe0f4"/>
|
||||
<path d="M310 118 L400 100 L452 150 L420 210 L370 222 L322 176 Z" fill="#2763ad"/>
|
||||
<path d="M370 222 L420 210 L490 238 L470 310 L400 330 L340 290 Z" fill="#73a6dd"/>
|
||||
<path d="M310 352 L340 290 L400 330 L392 384 L330 396 Z" fill="#a4c6ea"/>
|
||||
<path d="M400 100 L480 80 L540 112 L520 176 L452 150 Z" fill="#4785cd"/>
|
||||
<path d="M452 150 L520 176 L560 220 L490 238 L420 210 Z" fill="#16447d"/>
|
||||
<path d="M490 238 L560 220 L620 258 L600 320 L530 330 L470 310 Z" fill="#a4c6ea"/>
|
||||
<path d="M540 112 L620 96 L680 130 L640 190 L560 220 L520 176 Z" fill="#73a6dd"/>
|
||||
<path d="M560 220 L640 190 L700 214 L690 262 L620 258 Z" fill="#2763ad"/>
|
||||
<path d="M400 330 L470 310 L530 330 L520 380 L450 396 L392 384 Z" fill="#cfe0f4"/>
|
||||
</g>
|
||||
<path d="M452 150 L520 176 L560 220 L490 238 L420 210 Z" fill="none" stroke="#0f172a" stroke-width="4" stroke-linejoin="round"/>
|
||||
<g transform="translate(560 384)">
|
||||
<rect x="-8" y="-14" width="212" height="48" rx="10" fill="#ffffff" fill-opacity="0.94" stroke="#e2e8f0"/>
|
||||
<rect x="4" y="-4" width="28" height="12" fill="#eef4fb"/>
|
||||
<rect x="32" y="-4" width="28" height="12" fill="#cfe0f4"/>
|
||||
<rect x="60" y="-4" width="28" height="12" fill="#a4c6ea"/>
|
||||
<rect x="88" y="-4" width="28" height="12" fill="#73a6dd"/>
|
||||
<rect x="116" y="-4" width="28" height="12" fill="#4785cd"/>
|
||||
<rect x="144" y="-4" width="28" height="12" fill="#2763ad"/>
|
||||
<rect x="172" y="-4" width="24" height="12" fill="#16447d"/>
|
||||
<rect x="4" y="16" width="120" height="6" rx="3" fill="#cbd5e1"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.5 KiB |
|
|
@ -1,85 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 450">
|
||||
<defs>
|
||||
<linearGradient id="land" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#eef2ec"/>
|
||||
<stop offset="1" stop-color="#e3e8e1"/>
|
||||
</linearGradient>
|
||||
<filter id="shadow" x="-20%" y="-20%" width="140%" height="140%">
|
||||
<feDropShadow dx="0" dy="1.5" stdDeviation="2" flood-color="#0f172a" flood-opacity="0.3"/>
|
||||
</filter>
|
||||
</defs>
|
||||
<rect width="800" height="450" fill="url(#land)"/>
|
||||
<path d="M800 40 C720 70 640 110 560 150 C500 180 450 190 400 186 C380 200 390 230 430 240 C520 262 600 300 660 360 C700 400 740 430 800 450 Z" fill="#cfe0ee"/>
|
||||
<path d="M400 186 C350 176 300 168 250 170 C200 172 160 180 120 186 C100 196 120 214 160 210 C220 204 290 206 360 214 C385 216 395 202 400 186 Z" fill="#cfe0ee"/>
|
||||
<path d="M120 190 C90 196 60 200 0 214" fill="none" stroke="#cfe0ee" stroke-width="12" stroke-linecap="round"/>
|
||||
<g filter="url(#shadow)" stroke="#ffffff" stroke-width="1.5">
|
||||
<g transform="translate(560 214)">
|
||||
<circle r="44" fill="#2a78d6"/>
|
||||
<path d="M0 -44 A44 44 0 0 1 41.8 13.6 L0 0 Z" fill="#eb6834"/>
|
||||
<path d="M41.8 13.6 A44 44 0 0 1 27 34.7 L0 0 Z" fill="#1baf7a"/>
|
||||
<path d="M27 34.7 A44 44 0 0 1 14 41.7 L0 0 Z" fill="#eda100"/>
|
||||
<circle r="24" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(470 202)">
|
||||
<circle r="30" fill="#2a78d6"/>
|
||||
<path d="M0 -30 A30 30 0 0 1 28.5 9.3 L0 0 Z" fill="#eb6834"/>
|
||||
<path d="M28.5 9.3 A30 30 0 0 1 17.6 24.3 L0 0 Z" fill="#1baf7a"/>
|
||||
<circle r="16" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(680 322)">
|
||||
<circle r="34" fill="#2a78d6"/>
|
||||
<path d="M0 -34 A34 34 0 0 1 32.3 10.5 L0 0 Z" fill="#eb6834"/>
|
||||
<path d="M32.3 10.5 A34 34 0 0 1 10.5 32.3 L0 0 Z" fill="#1baf7a"/>
|
||||
<circle r="18" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(300 186)">
|
||||
<circle r="32" fill="#2a78d6"/>
|
||||
<path d="M0 -32 A32 32 0 0 1 30.4 -9.9 L0 0 Z" fill="#eb6834"/>
|
||||
<path d="M30.4 -9.9 A32 32 0 0 1 22.6 22.6 L0 0 Z" fill="#1baf7a"/>
|
||||
<circle r="17" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(372 196)">
|
||||
<circle r="22" fill="#2a78d6"/>
|
||||
<path d="M0 -22 A22 22 0 0 1 20.9 6.8 L0 0 Z" fill="#eb6834"/>
|
||||
<circle r="12" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(616 262)">
|
||||
<circle r="20" fill="#2a78d6"/>
|
||||
<path d="M0 -20 A20 20 0 0 1 19 6.2 L0 0 Z" fill="#eb6834"/>
|
||||
<circle r="11" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(200 186)">
|
||||
<circle r="18" fill="#2a78d6"/>
|
||||
<path d="M0 -18 A18 18 0 0 1 17.1 5.6 L0 0 Z" fill="#1baf7a"/>
|
||||
<circle r="10" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(140 200)">
|
||||
<circle r="13" fill="#2a78d6"/>
|
||||
<path d="M0 -13 A13 13 0 0 1 12.4 4 L0 0 Z" fill="#eb6834"/>
|
||||
<circle r="7" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(60 205)">
|
||||
<circle r="10" fill="#2a78d6"/>
|
||||
<circle r="5.5" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
<g transform="translate(730 380)">
|
||||
<circle r="16" fill="#2a78d6"/>
|
||||
<path d="M0 -16 A16 16 0 0 1 15.2 4.9 L0 0 Z" fill="#eb6834"/>
|
||||
<circle r="9" fill="#ffffff" stroke="none"/>
|
||||
</g>
|
||||
</g>
|
||||
<g transform="translate(250 392)">
|
||||
<rect x="0" y="0" width="300" height="38" rx="10" fill="#ffffff" stroke="#e2e8f0"/>
|
||||
<circle cx="25" cy="19" r="13" fill="#2563eb"/>
|
||||
<path d="M21 13 L31 19 L21 25 Z" fill="#ffffff"/>
|
||||
<g font-family="system-ui, sans-serif" font-size="13" text-anchor="middle">
|
||||
<rect x="50" y="8" width="240" height="22" rx="6" fill="#ffffff" stroke="#e2e8f0"/>
|
||||
<rect x="146" y="8" width="48" height="22" fill="#2563eb"/>
|
||||
<text x="74" y="24" fill="#0f172a">2021</text>
|
||||
<text x="122" y="24" fill="#0f172a">2022</text>
|
||||
<text x="170" y="24" fill="#ffffff" font-weight="600">2023</text>
|
||||
<text x="218" y="24" fill="#0f172a">2024</text>
|
||||
<text x="266" y="24" fill="#0f172a">2025</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 4 KiB |
|
|
@ -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() {
|
|||
<Route path="/verkehr/thurgau" element={<TrafficThurgauPage />} />
|
||||
<Route path="/schifffahrt/thurgau" element={<WatercraftThurgauPage />} />
|
||||
<Route path="/fahrzeuge/thurgau" element={<VehiclesThurgauPage />} />
|
||||
<Route path="/karte/thurgau" element={<ThurgauCombinedPage />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -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 =
|
||||
'<a href="https://data.tg.ch/explore/dataset/dbu-tba-1/">Kanton Thurgau</a>';
|
||||
'Verkehr: <a href="https://data.tg.ch/explore/dataset/dbu-tba-1/">Kanton Thurgau</a>';
|
||||
|
||||
export function TrafficMap({
|
||||
export function TrafficLayer({
|
||||
stations,
|
||||
day,
|
||||
hour,
|
||||
selectedCode,
|
||||
onSelect,
|
||||
onAnimatorReady,
|
||||
}: TrafficMapProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const mapRef = useRef<L.Map | null>(null);
|
||||
fitToData = true,
|
||||
}: TrafficLayerProps) {
|
||||
const map = useMap();
|
||||
useMapAttribution(DATA_ATTRIBUTION);
|
||||
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 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 <div ref={containerRef} className="traffic-map" />;
|
||||
return null;
|
||||
}
|
||||
44
client/src/components/combined/LayerCard.tsx
Normal file
44
client/src/components/combined/LayerCard.tsx
Normal file
|
|
@ -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 (
|
||||
<section className={`layer-card ${active ? 'active' : ''}`}>
|
||||
<div className="layer-card-header">
|
||||
<label>
|
||||
<input type="checkbox" checked={active} onChange={onToggle} />
|
||||
<span className="layer-card-swatch" style={{ background: color }} />
|
||||
<span>
|
||||
<span className="layer-card-title">{title}</span>
|
||||
<span className="layer-card-subtitle">{subtitle}</span>
|
||||
</span>
|
||||
</label>
|
||||
<Link to={detailPath} className="layer-card-link" title={`Einzelkarte ${title}`}>
|
||||
Einzelkarte
|
||||
</Link>
|
||||
</div>
|
||||
{active && note && <p className="layer-card-note">{note}</p>}
|
||||
{active && children && <div className="layer-card-body">{children}</div>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
21
client/src/components/combined/LayerPanel.tsx
Normal file
21
client/src/components/combined/LayerPanel.tsx
Normal file
|
|
@ -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 (
|
||||
<div className={`layer-panel ${open ? 'open' : ''}`}>
|
||||
<button
|
||||
type="button"
|
||||
className="layer-panel-toggle"
|
||||
aria-expanded={open}
|
||||
onClick={() => setOpen(!open)}
|
||||
>
|
||||
Ebenen <span aria-hidden="true">{open ? '▴' : '▾'}</span>
|
||||
</button>
|
||||
{open && <div className="layer-cards">{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
81
client/src/components/combined/MunicipalityContext.tsx
Normal file
81
client/src/components/combined/MunicipalityContext.tsx
Normal file
|
|
@ -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 (
|
||||
<section className="municipality-context">
|
||||
<h3>In dieser Gemeinde</h3>
|
||||
|
||||
{stations &&
|
||||
(stations.length > 0 ? (
|
||||
<ul className="context-list">
|
||||
{stations.map((station) => {
|
||||
const total =
|
||||
dayByStation
|
||||
.get(station.code)
|
||||
?.directions.reduce((sum, d) => sum + sumCounts(d.hours[hour]), 0) ?? 0;
|
||||
return (
|
||||
<li key={station.code}>
|
||||
<button type="button" onClick={() => onSelectStation(station.code)}>
|
||||
<span className="context-kind">Zählstelle</span>
|
||||
<span className="context-name">{station.name}</span>
|
||||
<span className="context-value">
|
||||
{formatNumber(total)} Fz/h um {hourLabel}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="panel-note">Keine Verkehrszählstelle.</p>
|
||||
))}
|
||||
|
||||
{locations &&
|
||||
(locations.length > 0 ? (
|
||||
<ul className="context-list">
|
||||
{locations.map((location) => (
|
||||
<li key={location.name}>
|
||||
<button type="button" onClick={() => onSelectLocation(location.name)}>
|
||||
<span className="context-kind">Bootsstandort</span>
|
||||
<span className="context-name">{location.name}</span>
|
||||
<span className="context-value">
|
||||
{formatNumber(location.count)} Boote {year}
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="panel-note">Kein Bootsstandort.</p>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
119
client/src/components/combined/OverviewPanel.tsx
Normal file
119
client/src/components/combined/OverviewPanel.tsx
Normal file
|
|
@ -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 (
|
||||
<aside className="station-panel overview-panel">
|
||||
<header className="station-panel-header">
|
||||
<div>
|
||||
<h2>Kanton Thurgau</h2>
|
||||
<p>Alle eingeschalteten Ebenen auf einen Blick</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{!vehicles && !watercraft && !traffic && (
|
||||
<p className="panel-note">Schalte links mindestens eine Ebene ein.</p>
|
||||
)}
|
||||
|
||||
{vehicles && (
|
||||
<section>
|
||||
<h3>Fahrzeugbestand {year ?? ''}</h3>
|
||||
{vehicles.view ? (
|
||||
<div className="stat-tiles">
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{formatNumber(vehicles.view.canton.count)}</span>
|
||||
<span className="stat-tile-label">Strassenfahrzeuge</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{carDensity !== null ? formatNumber(carDensity) : '–'}
|
||||
</span>
|
||||
<span className="stat-tile-label">Personenwagen pro 1000 Einwohner</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="panel-note">
|
||||
Für {year} keine Daten, erst ab {vehicles.firstYear}.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{watercraft && (
|
||||
<section>
|
||||
<h3>Wasserfahrzeuge {year ?? ''}</h3>
|
||||
{watercraft.view ? (
|
||||
<div className="stat-tiles">
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{formatNumber(watercraft.view.canton.count)}
|
||||
</span>
|
||||
<span className="stat-tile-label">immatrikulierte Boote</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">
|
||||
{formatNumber(watercraft.view.locations.length)}
|
||||
</span>
|
||||
<span className="stat-tile-label">Standorte</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="panel-note">
|
||||
Für {year} keine Daten, erst ab {watercraft.firstYear}.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{traffic && (
|
||||
<section>
|
||||
<h3>
|
||||
Strassenverkehr
|
||||
{traffic.date &&
|
||||
` ${formatDate(traffic.date)}, ${String(traffic.hour).padStart(2, '0')}:00`}
|
||||
</h3>
|
||||
<div className="stat-tiles">
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{formatNumber(traffic.hourTotal)}</span>
|
||||
<span className="stat-tile-label">Fahrzeuge in dieser Stunde</span>
|
||||
</div>
|
||||
<div className="stat-tile">
|
||||
<span className="stat-tile-value">{traffic.stationCount}</span>
|
||||
<span className="stat-tile-label">Zählstellen</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="panel-note">
|
||||
Verkehrszählungen gibt es als Stundenwerte erst
|
||||
{traffic.firstDate && ` ab ${formatDate(traffic.firstDate, { weekday: undefined })}`}.
|
||||
Das gewählte Jahr gilt für sie nicht; Tag und Stunde stellst du unten ein.
|
||||
</p>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<p className="panel-note overview-hint">
|
||||
Klicke auf eine Gemeinde, einen Bootsstandort oder eine Zählstelle, um Details zu sehen.
|
||||
</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
|
@ -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({
|
|||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{children}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 =
|
||||
'<a href="https://data.tg.ch/explore/dataset/djs-stv-17/">Strassenverkehrsamt Thurgau</a>, ' +
|
||||
'Fahrzeuge: <a href="https://data.tg.ch/explore/dataset/djs-stv-17/">Strassenverkehrsamt Thurgau</a>, ' +
|
||||
'<a href="https://www.swisstopo.admin.ch/de/landschaftsmodell-swissboundaries3d">swissBOUNDARIES3D</a>';
|
||||
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<HTMLDivElement>(null);
|
||||
const mapRef = useRef<L.Map | null>(null);
|
||||
fillOpacity = 0.78,
|
||||
fitToData = true,
|
||||
}: VehicleLayerProps) {
|
||||
const map = useMap();
|
||||
useMapAttribution(DATA_ATTRIBUTION);
|
||||
const layersRef = useRef<Map<string, L.Polygon>>(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 <div ref={containerRef} className="traffic-map" />;
|
||||
return null;
|
||||
}
|
||||
|
||||
function tooltipHtml(
|
||||
|
|
@ -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<string>;
|
||||
selectedName: string | null;
|
||||
onSelect: (name: string) => void;
|
||||
fitToData?: boolean;
|
||||
}
|
||||
|
||||
const THURGAU_LAKE_CENTER: L.LatLngTuple = [47.6, 9.1];
|
||||
const DATA_ATTRIBUTION =
|
||||
'<a href="https://data.tg.ch/explore/dataset/djs-kpo-7/">Kantonspolizei Thurgau</a>';
|
||||
'Boote: <a href="https://data.tg.ch/explore/dataset/djs-kpo-7/">Kantonspolizei Thurgau</a>';
|
||||
|
||||
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<HTMLDivElement>(null);
|
||||
const mapRef = useRef<L.Map | null>(null);
|
||||
fitToData = true,
|
||||
}: WatercraftLayerProps) {
|
||||
const map = useMap();
|
||||
useMapAttribution(DATA_ATTRIBUTION);
|
||||
const markersRef = useRef<Map<string, L.Marker>>(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 <div ref={containerRef} className="traffic-map" />;
|
||||
return null;
|
||||
}
|
||||
|
||||
function donutSvg(
|
||||
48
client/src/map/MapHost.tsx
Normal file
48
client/src/map/MapHost.tsx
Normal file
|
|
@ -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<HTMLDivElement>(null);
|
||||
const initialViewRef = useRef({ center, zoom });
|
||||
const [map, setMap] = useState<L.Map | null>(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 (
|
||||
<>
|
||||
<div ref={containerRef} className="map-host" />
|
||||
{map && <MapContext.Provider value={map}>{children}</MapContext.Provider>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -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 = `© <a href="https://www.swisstopo.admin.ch/">swisstopo</a> · Daten: ${dataAttribution}`;
|
||||
export function addSwisstopoBaseLayers(map: L.Map): void {
|
||||
const attribution = '© <a href="https://www.swisstopo.admin.ch/">swisstopo</a>';
|
||||
const baseLayers: Record<string, L.TileLayer> = Object.fromEntries(
|
||||
BASE_MAPS.map((baseMap) => [
|
||||
baseMap.name,
|
||||
|
|
|
|||
88
client/src/map/geometry.ts
Normal file
88
client/src/map/geometry.ts
Normal file
|
|
@ -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<T>(
|
||||
outlines: Outline[],
|
||||
items: T[],
|
||||
position: (item: T) => [number, number] | null,
|
||||
maxDistanceMeters: number,
|
||||
): Map<string, T[]> {
|
||||
const result = new Map<string, T[]>();
|
||||
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);
|
||||
}
|
||||
24
client/src/map/mapContext.ts
Normal file
24
client/src/map/mapContext.ts
Normal file
|
|
@ -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<L.Map | null>(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]);
|
||||
}
|
||||
45
client/src/map/useYearPlayback.ts
Normal file
45
client/src/map/useYearPlayback.ts
Normal file
|
|
@ -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 };
|
||||
}
|
||||
|
|
@ -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',
|
||||
},
|
||||
];
|
||||
|
|
|
|||
476
client/src/pages/ThurgauCombinedPage.tsx
Normal file
476
client/src/pages/ThurgauCombinedPage.tsx
Normal file
|
|
@ -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<LayerKey> {
|
||||
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<Selection | null>(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 = (
|
||||
<MemoMunicipalityPanel
|
||||
meta={vehicles.meta}
|
||||
years={vehicles.years}
|
||||
id={id}
|
||||
year={year}
|
||||
metric={vehicles.metric}
|
||||
metricTitle={vehicles.title}
|
||||
onClose={clearSelection}
|
||||
>
|
||||
<MunicipalityContext
|
||||
stations={showTraffic ? (stationsByMunicipality.get(id) ?? []) : null}
|
||||
locations={showBoats && boatView ? (locationsByMunicipality.get(id) ?? []) : null}
|
||||
day={traffic.day}
|
||||
hour={traffic.hour}
|
||||
year={year}
|
||||
onSelectStation={selectStation}
|
||||
onSelectLocation={selectLocation}
|
||||
/>
|
||||
</MemoMunicipalityPanel>
|
||||
);
|
||||
} else if (
|
||||
visibleSelection?.layer === 'boote' &&
|
||||
watercraft.meta &&
|
||||
watercraft.dimension &&
|
||||
year !== null
|
||||
) {
|
||||
panel = (
|
||||
<MemoLocationPanel
|
||||
meta={watercraft.meta}
|
||||
years={watercraft.years}
|
||||
name={visibleSelection.name}
|
||||
year={year}
|
||||
dimension={watercraft.dimension}
|
||||
groups={watercraft.groups}
|
||||
hidden={watercraft.hidden}
|
||||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else if (selectedStation) {
|
||||
panel = (
|
||||
<MemoStationPanel
|
||||
station={selectedStation}
|
||||
day={traffic.day}
|
||||
hour={traffic.hour}
|
||||
onClose={clearSelection}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
panel = (
|
||||
<OverviewPanel
|
||||
year={year}
|
||||
vehicles={
|
||||
showVehicles && vehicles.meta
|
||||
? { meta: vehicles.meta, view: vehicleView, firstYear: vehicles.yearNumbers[0] }
|
||||
: null
|
||||
}
|
||||
watercraft={showBoats ? { view: boatView, firstYear: watercraft.yearNumbers[0] } : null}
|
||||
traffic={
|
||||
showTraffic
|
||||
? {
|
||||
stationCount: traffic.stations.length,
|
||||
date: traffic.date,
|
||||
hour: traffic.hour,
|
||||
hourTotal: traffic.hourTotal,
|
||||
firstDate: traffic.dates[0] ?? null,
|
||||
}
|
||||
: null
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const error =
|
||||
(showVehicles ? vehicles.error : null) ??
|
||||
(showBoats ? watercraft.error : null) ??
|
||||
(showTraffic ? traffic.error : null);
|
||||
const loading =
|
||||
(showVehicles && vehicles.loading) ||
|
||||
(showBoats && watercraft.loading) ||
|
||||
(showTraffic && traffic.loading);
|
||||
|
||||
const missingYearNote = (firstYear: number | undefined) =>
|
||||
year !== null && firstYear !== undefined && year < firstYear
|
||||
? `Keine Daten für ${year}, erst ab ${firstYear}.`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div className="app with-panel">
|
||||
<header className="app-header">
|
||||
<div className="title-row">
|
||||
<Link to="/" className="back-link" aria-label="Zur Übersicht" title="Zur Übersicht">
|
||||
←
|
||||
</Link>
|
||||
<div className="title">
|
||||
<h1>
|
||||
<Link to="/" className="brand-link">
|
||||
OpenDataVisualizer
|
||||
</Link>{' '}
|
||||
<span className="title-separator">/</span> Thurgau – alle Daten
|
||||
</h1>
|
||||
<span className="subtitle">
|
||||
Fahrzeugbestand, Wasserfahrzeuge und Strassenverkehr auf einer Karte
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="stats">
|
||||
{showVehicles && vehicleView && (
|
||||
<div>
|
||||
<span className="stat-value">{formatNumber(vehicleView.canton.count)}</span>
|
||||
<span className="stat-label">Fahrzeuge {vehicleView.year}</span>
|
||||
</div>
|
||||
)}
|
||||
{showBoats && boatView && (
|
||||
<div>
|
||||
<span className="stat-value">{formatNumber(boatView.canton.count)}</span>
|
||||
<span className="stat-label">Boote {boatView.year}</span>
|
||||
</div>
|
||||
)}
|
||||
{showTraffic && (
|
||||
<div>
|
||||
<span className="stat-value">{formatNumber(traffic.hourTotal)}</span>
|
||||
<span className="stat-label">Fahrzeuge in dieser Stunde</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="map-area">
|
||||
<MapHost center={THURGAU_CENTER} zoom={10.5}>
|
||||
{showVehicles && (
|
||||
<VehicleLayer
|
||||
shapes={vehicles.shapes}
|
||||
areas={vehicleView?.municipalities ?? []}
|
||||
metric={vehicles.metric}
|
||||
metricTitle={vehicles.title}
|
||||
scale={vehicles.scale}
|
||||
selectedId={visibleSelection?.layer === 'fahrzeuge' ? visibleSelection.id : null}
|
||||
onSelect={selectMunicipality}
|
||||
fillOpacity={showBoats || showTraffic ? SHARED_FILL_OPACITY : undefined}
|
||||
fitToData={false}
|
||||
/>
|
||||
)}
|
||||
{showTraffic && (
|
||||
<TrafficLayer
|
||||
stations={traffic.stations}
|
||||
day={traffic.day}
|
||||
hour={traffic.hour}
|
||||
selectedCode={visibleSelection?.layer === 'verkehr' ? visibleSelection.code : null}
|
||||
onSelect={selectStation}
|
||||
onAnimatorReady={traffic.handleAnimatorReady}
|
||||
fitToData={false}
|
||||
/>
|
||||
)}
|
||||
{showBoats && (
|
||||
<WatercraftLayer
|
||||
locations={boatView?.locations ?? []}
|
||||
dimension={watercraft.dimension}
|
||||
groups={watercraft.groups}
|
||||
hidden={watercraft.hidden}
|
||||
selectedName={visibleSelection?.layer === 'boote' ? visibleSelection.name : null}
|
||||
onSelect={selectLocation}
|
||||
fitToData={false}
|
||||
/>
|
||||
)}
|
||||
</MapHost>
|
||||
|
||||
<LayerPanel>
|
||||
<LayerCard
|
||||
title="Fahrzeugbestand"
|
||||
subtitle="Gemeinden · pro Jahr"
|
||||
color="#4785cd"
|
||||
active={showVehicles}
|
||||
detailPath="/fahrzeuge/thurgau"
|
||||
note={missingYearNote(vehicles.yearNumbers[0])}
|
||||
onToggle={() => toggleLayer('fahrzeuge')}
|
||||
>
|
||||
{vehicles.meta && vehicleView && (
|
||||
<MetricControls
|
||||
meta={vehicles.meta}
|
||||
canton={vehicleView.canton}
|
||||
metric={vehicles.metric}
|
||||
scale={vehicles.scale}
|
||||
onMetricChange={vehicles.setMetric}
|
||||
/>
|
||||
)}
|
||||
</LayerCard>
|
||||
<LayerCard
|
||||
title="Wasserfahrzeuge"
|
||||
subtitle="Bootsstandorte · pro Jahr"
|
||||
color="#eb6834"
|
||||
active={showBoats}
|
||||
detailPath="/schifffahrt/thurgau"
|
||||
note={missingYearNote(watercraft.yearNumbers[0])}
|
||||
onToggle={() => toggleLayer('boote')}
|
||||
>
|
||||
{watercraft.meta && watercraft.dimension && boatView && (
|
||||
<CategoryLegend
|
||||
dimensions={watercraft.meta.dimensions}
|
||||
dimension={watercraft.dimension}
|
||||
groups={watercraft.groups}
|
||||
counts={boatLegendCounts}
|
||||
hidden={watercraft.hidden}
|
||||
onDimensionChange={watercraft.setDimension}
|
||||
onToggle={watercraft.toggleGroup}
|
||||
onShowAll={watercraft.showAllGroups}
|
||||
/>
|
||||
)}
|
||||
{unplaced.map((location) => (
|
||||
<button
|
||||
key={location.name}
|
||||
type="button"
|
||||
className={`link-button unplaced-link ${
|
||||
visibleSelection?.layer === 'boote' && visibleSelection.name === location.name
|
||||
? 'active'
|
||||
: ''
|
||||
}`}
|
||||
onClick={() => selectLocation(location.name)}
|
||||
>
|
||||
{location.name}: {formatNumber(location.count)} Boote (nicht auf der Karte)
|
||||
</button>
|
||||
))}
|
||||
</LayerCard>
|
||||
<LayerCard
|
||||
title="Strassenverkehr"
|
||||
subtitle="Zählstellen · pro Stunde"
|
||||
color="#334155"
|
||||
active={showTraffic}
|
||||
detailPath="/verkehr/thurgau"
|
||||
note={
|
||||
traffic.dates.length > 0
|
||||
? `Stundenwerte ${formatDate(traffic.dates[0], { weekday: undefined })} bis ${formatDate(traffic.dates[traffic.dates.length - 1], { weekday: undefined })}; das gewählte Jahr gilt hier nicht.`
|
||||
: null
|
||||
}
|
||||
onToggle={() => toggleLayer('verkehr')}
|
||||
>
|
||||
<Legend />
|
||||
</LayerCard>
|
||||
</LayerPanel>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
{yearEntries.length > 0 && year !== null && (
|
||||
<YearControls
|
||||
years={yearEntries}
|
||||
year={year}
|
||||
playing={playing}
|
||||
onYearChange={setYear}
|
||||
onPlayingChange={setPlaying}
|
||||
/>
|
||||
)}
|
||||
{showTraffic && traffic.date && (
|
||||
<TimeControls
|
||||
dates={traffic.dates}
|
||||
date={traffic.date}
|
||||
time={traffic.time}
|
||||
playing={traffic.playing}
|
||||
hoursPerSecond={traffic.hoursPerSecond}
|
||||
onDateChange={traffic.setDate}
|
||||
onTimeChange={traffic.handleTimeChange}
|
||||
onPlayingChange={traffic.setPlaying}
|
||||
onSpeedChange={traffic.setHoursPerSecond}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div className="notice">
|
||||
Daten werden geladen… (beim ersten Start holt der Server sie von data.tg.ch und
|
||||
swisstopo)
|
||||
</div>
|
||||
)}
|
||||
{error && <div className="notice error">Fehler beim Laden: {String(error.message)}</div>}
|
||||
</main>
|
||||
|
||||
{panel}
|
||||
|
||||
<footer className="app-footer">
|
||||
Quellen:{' '}
|
||||
{vehicles.meta && (
|
||||
<>
|
||||
<DatasetCredit
|
||||
title={vehicles.meta.title}
|
||||
publisher={vehicles.meta.publisher}
|
||||
url={vehicles.meta.sourceUrl}
|
||||
license={vehicles.meta.license}
|
||||
/>{' '}
|
||||
·{' '}
|
||||
<DatasetCredit
|
||||
title={vehicles.meta.populationTitle}
|
||||
publisher={vehicles.meta.populationPublisher}
|
||||
url={vehicles.meta.populationSourceUrl}
|
||||
license={vehicles.meta.populationLicense}
|
||||
/>{' '}
|
||||
·{' '}
|
||||
</>
|
||||
)}
|
||||
{watercraft.meta && (
|
||||
<>
|
||||
<DatasetCredit
|
||||
title={watercraft.meta.title}
|
||||
publisher={watercraft.meta.publisher}
|
||||
url={watercraft.meta.sourceUrl}
|
||||
license={watercraft.meta.license}
|
||||
/>{' '}
|
||||
·{' '}
|
||||
</>
|
||||
)}
|
||||
<a href={traffic.meta?.sourceUrl} target="_blank" rel="noreferrer">
|
||||
{traffic.meta?.publisher ?? 'Kanton Thurgau'}
|
||||
</a>{' '}
|
||||
(Verkehrszählungen, Lizenz <LicenseLink license={traffic.meta?.license ?? 'CC0 1.0'} />) ·
|
||||
Karten, Gemeindegrenzen und Strassennetz © swisstopo · Bearbeitung: Werte pro Gemeinde,
|
||||
Standort und Zählstelle aggregiert, Zuordnung zu Gemeinden über die Lage
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,110 +1,31 @@
|
|||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { memo, useCallback, useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { fetchDay, fetchMeta, fetchStations } from '../api/traffic';
|
||||
import { LicenseLink } from '../components/DatasetCredit';
|
||||
import { Legend } from '../components/Legend';
|
||||
import { StationPanel } from '../components/StationPanel';
|
||||
import { SPEEDS, TimeControls } from '../components/TimeControls';
|
||||
import { TrafficMap } from '../components/TrafficMap';
|
||||
import type { FlowAnimator } from '../traffic/flowAnimator';
|
||||
import { TimeControls } from '../components/TimeControls';
|
||||
import { TrafficLayer } from '../components/TrafficLayer';
|
||||
import { THURGAU_CENTER } from '../map/baseLayers';
|
||||
import { MapHost } from '../map/MapHost';
|
||||
import { formatNumber } from '../traffic/format';
|
||||
import { sumCounts } from '../traffic/vehicleClasses';
|
||||
import { useTrafficData } from '../traffic/useTrafficData';
|
||||
|
||||
const MemoStationPanel = memo(StationPanel);
|
||||
|
||||
const INITIAL_TIME = 7.5;
|
||||
|
||||
export function TrafficThurgauPage() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['meta'],
|
||||
queryFn: fetchMeta,
|
||||
refetchInterval: 10 * 60_000,
|
||||
});
|
||||
const stationsQuery = useQuery({
|
||||
queryKey: ['stations'],
|
||||
queryFn: fetchStations,
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.some((s) => s.directions.some((d) => d.path.length < 2)) ? 30_000 : false,
|
||||
});
|
||||
|
||||
const dates = useMemo(() => metaQuery.data?.dates ?? [], [metaQuery.data]);
|
||||
const [date, setDate] = useState<string | null>(null);
|
||||
const [time, setTime] = useState(INITIAL_TIME);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond);
|
||||
const traffic = useTrafficData();
|
||||
const { stations, dates, date, day, hour, hourTotal } = traffic;
|
||||
const [selectedCode, setSelectedCode] = useState<number | null>(null);
|
||||
const animatorRef = useRef<FlowAnimator | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = 'Strassenverkehr Thurgau – OpenDataVisualizer';
|
||||
}, []);
|
||||
|
||||
const datesRef = useRef(dates);
|
||||
datesRef.current = dates;
|
||||
|
||||
useEffect(() => {
|
||||
if (!date && dates.length > 0) {
|
||||
setDate(dates[dates.length - 1]);
|
||||
}
|
||||
}, [date, dates]);
|
||||
|
||||
const dayQuery = useQuery({
|
||||
queryKey: ['day', date],
|
||||
queryFn: () => fetchDay(date!),
|
||||
enabled: !!date,
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
const day = dayQuery.data ?? null;
|
||||
|
||||
const handleAnimatorReady = useCallback((animator: FlowAnimator) => {
|
||||
animatorRef.current = animator;
|
||||
animator.time = INITIAL_TIME;
|
||||
animator.onTick = setTime;
|
||||
animator.onDayEnd = () =>
|
||||
setDate((current) => {
|
||||
const all = datesRef.current;
|
||||
const index = current ? all.indexOf(current) : -1;
|
||||
return all.length === 0 ? current : all[(index + 1) % all.length];
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.playing = playing;
|
||||
}
|
||||
}, [playing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.hoursPerSecond = hoursPerSecond;
|
||||
}
|
||||
}, [hoursPerSecond]);
|
||||
|
||||
const handleTimeChange = useCallback((value: number) => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.time = value;
|
||||
}
|
||||
setTime(value);
|
||||
}, []);
|
||||
|
||||
const handleClose = useCallback(() => setSelectedCode(null), []);
|
||||
|
||||
const hour = Math.min(23, Math.floor(time));
|
||||
const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]);
|
||||
const selectedStation = stations.find((s) => s.code === selectedCode) ?? null;
|
||||
const meta = traffic.meta;
|
||||
|
||||
const hourTotal = useMemo(
|
||||
() =>
|
||||
day?.stations.reduce(
|
||||
(sum, station) =>
|
||||
sum + station.directions.reduce((s, d) => s + sumCounts(d.hours[hour]), 0),
|
||||
0,
|
||||
) ?? 0,
|
||||
[day, hour],
|
||||
);
|
||||
|
||||
const error = metaQuery.error ?? stationsQuery.error ?? dayQuery.error;
|
||||
const { error } = traffic;
|
||||
|
||||
return (
|
||||
<div className={`app ${selectedStation ? 'with-panel' : ''}`}>
|
||||
|
|
@ -136,33 +57,35 @@ export function TrafficThurgauPage() {
|
|||
</header>
|
||||
|
||||
<main className="map-area">
|
||||
<TrafficMap
|
||||
stations={stations}
|
||||
day={day}
|
||||
hour={hour}
|
||||
selectedCode={selectedCode}
|
||||
onSelect={setSelectedCode}
|
||||
onAnimatorReady={handleAnimatorReady}
|
||||
/>
|
||||
<MapHost center={THURGAU_CENTER}>
|
||||
<TrafficLayer
|
||||
stations={stations}
|
||||
day={day}
|
||||
hour={hour}
|
||||
selectedCode={selectedCode}
|
||||
onSelect={setSelectedCode}
|
||||
onAnimatorReady={traffic.handleAnimatorReady}
|
||||
/>
|
||||
</MapHost>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
{date && (
|
||||
<TimeControls
|
||||
dates={dates}
|
||||
date={date}
|
||||
time={time}
|
||||
playing={playing}
|
||||
hoursPerSecond={hoursPerSecond}
|
||||
onDateChange={setDate}
|
||||
onTimeChange={handleTimeChange}
|
||||
onPlayingChange={setPlaying}
|
||||
onSpeedChange={setHoursPerSecond}
|
||||
time={traffic.time}
|
||||
playing={traffic.playing}
|
||||
hoursPerSecond={traffic.hoursPerSecond}
|
||||
onDateChange={traffic.setDate}
|
||||
onTimeChange={traffic.handleTimeChange}
|
||||
onPlayingChange={traffic.setPlaying}
|
||||
onSpeedChange={traffic.setHoursPerSecond}
|
||||
/>
|
||||
)}
|
||||
<Legend />
|
||||
</div>
|
||||
|
||||
{(metaQuery.isLoading || (metaQuery.data && dates.length === 0)) && (
|
||||
{traffic.loading && (
|
||||
<div className="notice">
|
||||
Verkehrsdaten werden geladen… (erster Start lädt die Daten von data.tg.ch)
|
||||
</div>
|
||||
|
|
@ -176,13 +99,13 @@ export function TrafficThurgauPage() {
|
|||
|
||||
<footer className="app-footer">
|
||||
Quelle:{' '}
|
||||
<a href={metaQuery.data?.sourceUrl} target="_blank" rel="noreferrer">
|
||||
{metaQuery.data?.publisher ?? 'Kanton Thurgau'}
|
||||
<a href={meta?.sourceUrl} target="_blank" rel="noreferrer">
|
||||
{meta?.publisher ?? 'Kanton Thurgau'}
|
||||
</a>{' '}
|
||||
· Lizenz <LicenseLink license={metaQuery.data?.license ?? 'CC0 1.0'} /> · Karten und
|
||||
Strassennetz © swisstopo
|
||||
{metaQuery.data?.lastRefresh &&
|
||||
` · aktualisiert ${new Date(metaQuery.data.lastRefresh).toLocaleString('de-CH')}`}
|
||||
· Lizenz <LicenseLink license={meta?.license ?? 'CC0 1.0'} /> · Karten und Strassennetz ©
|
||||
swisstopo
|
||||
{meta?.lastRefresh &&
|
||||
` · aktualisiert ${new Date(meta.lastRefresh).toLocaleString('de-CH')}`}
|
||||
</footer>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -1,84 +1,31 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import { fetchMunicipalityShapes, fetchVehicleMeta, fetchVehicleYears } from '../api/vehicles';
|
||||
import { memo, useCallback, useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { DatasetCredit } from '../components/DatasetCredit';
|
||||
import { MetricControls } from '../components/vehicles/MetricControls';
|
||||
import { MunicipalityPanel } from '../components/vehicles/MunicipalityPanel';
|
||||
import { VehicleMap } from '../components/vehicles/VehicleMap';
|
||||
import { VehicleLayer } from '../components/vehicles/VehicleLayer';
|
||||
import { THURGAU_CENTER } from '../map/baseLayers';
|
||||
import { MapHost } from '../map/MapHost';
|
||||
import { useYearPlayback } from '../map/useYearPlayback';
|
||||
import { YearControls } from '../components/watercraft/YearControls';
|
||||
import { formatNumber } from '../traffic/format';
|
||||
import { buildScale, metricTitle, metricValue, type Metric } from '../vehicles/metrics';
|
||||
import { metricValue } from '../vehicles/metrics';
|
||||
import { useVehicleData } from '../vehicles/useVehicleData';
|
||||
|
||||
const MemoMunicipalityPanel = memo(MunicipalityPanel);
|
||||
|
||||
const PLAY_INTERVAL_MS = 1600;
|
||||
|
||||
export function VehiclesThurgauPage() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['vehicle-meta'],
|
||||
queryFn: fetchVehicleMeta,
|
||||
refetchInterval: (query) => (query.state.data?.years.length ? false : 15_000),
|
||||
});
|
||||
const ready = !!metaQuery.data?.years.length;
|
||||
const lastRefresh = metaQuery.data?.lastRefresh ?? null;
|
||||
const yearsQuery = useQuery({
|
||||
queryKey: ['vehicle-years', lastRefresh],
|
||||
queryFn: fetchVehicleYears,
|
||||
enabled: ready,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const shapesQuery = useQuery({
|
||||
queryKey: ['vehicle-shapes', lastRefresh],
|
||||
queryFn: fetchMunicipalityShapes,
|
||||
enabled: ready,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [metric, setMetric] = useState<Metric>({ kind: 'density', group: 0 });
|
||||
const vehicles = useVehicleData();
|
||||
const { meta, years, shapes, metric, scale, title } = vehicles;
|
||||
const { year, setYear, playing, setPlaying } = useYearPlayback(vehicles.yearNumbers);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = 'Fahrzeugbestand Thurgau – OpenDataVisualizer';
|
||||
}, []);
|
||||
|
||||
const meta = metaQuery.data;
|
||||
const years = useMemo(() => yearsQuery.data ?? [], [yearsQuery.data]);
|
||||
const shapes = useMemo(() => shapesQuery.data ?? [], [shapesQuery.data]);
|
||||
const requestedYear = Number(searchParams.get('jahr'));
|
||||
const year = years.some((y) => y.year === requestedYear)
|
||||
? requestedYear
|
||||
: (years[years.length - 1]?.year ?? null);
|
||||
const view = years.find((y) => y.year === year) ?? null;
|
||||
|
||||
const setYear = useCallback(
|
||||
(value: number) =>
|
||||
setSearchParams(
|
||||
(params) => {
|
||||
params.set('jahr', String(value));
|
||||
return params;
|
||||
},
|
||||
{ replace: true },
|
||||
),
|
||||
[setSearchParams],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing || years.length < 2 || year === null) {
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
const index = years.findIndex((y) => y.year === year);
|
||||
setYear(years[(index + 1) % years.length].year);
|
||||
}, PLAY_INTERVAL_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [playing, years, year, setYear]);
|
||||
|
||||
const scale = useMemo(() => buildScale(years, metric), [years, metric]);
|
||||
const title = meta ? metricTitle(metric, meta) : '';
|
||||
|
||||
const handleClose = useCallback(() => setSelectedId(null), []);
|
||||
const handleSelect = useCallback(
|
||||
(id: string) => setSelectedId((current) => (current === id ? null : id)),
|
||||
|
|
@ -91,8 +38,7 @@ export function VehiclesThurgauPage() {
|
|||
const carDensity =
|
||||
view && carIndex >= 0 ? metricValue(view.canton, { kind: 'density', group: carIndex }) : null;
|
||||
|
||||
const error = metaQuery.error ?? yearsQuery.error ?? shapesQuery.error;
|
||||
const loading = metaQuery.isLoading || (meta && meta.years.length === 0) || yearsQuery.isLoading;
|
||||
const { error, loading } = vehicles;
|
||||
|
||||
return (
|
||||
<div className="app with-panel">
|
||||
|
|
@ -139,15 +85,17 @@ export function VehiclesThurgauPage() {
|
|||
</header>
|
||||
|
||||
<main className="map-area">
|
||||
<VehicleMap
|
||||
shapes={shapes}
|
||||
areas={view?.municipalities ?? []}
|
||||
metric={metric}
|
||||
metricTitle={title}
|
||||
scale={scale}
|
||||
selectedId={selectedId}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
<MapHost center={THURGAU_CENTER}>
|
||||
<VehicleLayer
|
||||
shapes={shapes}
|
||||
areas={view?.municipalities ?? []}
|
||||
metric={metric}
|
||||
metricTitle={title}
|
||||
scale={scale}
|
||||
selectedId={selectedId}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
</MapHost>
|
||||
|
||||
<div className="overlay-bottom">
|
||||
{meta && year !== null && (
|
||||
|
|
@ -165,7 +113,7 @@ export function VehiclesThurgauPage() {
|
|||
canton={view.canton}
|
||||
metric={metric}
|
||||
scale={scale}
|
||||
onMetricChange={setMetric}
|
||||
onMetricChange={vehicles.setMetric}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,99 +1,33 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import { fetchWatercraftMeta, fetchWatercraftYears, type DimensionKey } from '../api/watercraft';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { DatasetCredit } from '../components/DatasetCredit';
|
||||
import { CategoryLegend } from '../components/watercraft/CategoryLegend';
|
||||
import { LocationPanel } from '../components/watercraft/LocationPanel';
|
||||
import { WatercraftMap } from '../components/watercraft/WatercraftMap';
|
||||
import { WatercraftLayer } from '../components/watercraft/WatercraftLayer';
|
||||
import { THURGAU_LAKE_CENTER } from '../map/baseLayers';
|
||||
import { MapHost } from '../map/MapHost';
|
||||
import { useYearPlayback } from '../map/useYearPlayback';
|
||||
import { YearControls } from '../components/watercraft/YearControls';
|
||||
import { formatNumber } from '../traffic/format';
|
||||
import { buildGroups, groupCounts } from '../watercraft/categories';
|
||||
import { useWatercraftData } from '../watercraft/useWatercraftData';
|
||||
|
||||
const MemoLocationPanel = memo(LocationPanel);
|
||||
|
||||
const PLAY_INTERVAL_MS = 1600;
|
||||
const ELECTRIC = 'Elektrizität';
|
||||
|
||||
export function WatercraftThurgauPage() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['watercraft-meta'],
|
||||
queryFn: fetchWatercraftMeta,
|
||||
refetchInterval: (query) => (query.state.data?.years.length ? false : 15_000),
|
||||
});
|
||||
const yearsQuery = useQuery({
|
||||
queryKey: ['watercraft-years', metaQuery.data?.lastRefresh ?? null],
|
||||
queryFn: fetchWatercraftYears,
|
||||
enabled: !!metaQuery.data?.years.length,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [dimensionKey, setDimensionKey] = useState<DimensionKey>('type');
|
||||
const [hidden, setHidden] = useState<Set<string>>(() => new Set());
|
||||
const watercraft = useWatercraftData();
|
||||
const { meta, years, dimension, groups, hidden } = watercraft;
|
||||
const { year, setYear, playing, setPlaying } = useYearPlayback(watercraft.yearNumbers);
|
||||
const [selectedName, setSelectedName] = useState<string | null>(null);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = 'Wasserfahrzeuge Thurgau – OpenDataVisualizer';
|
||||
}, []);
|
||||
|
||||
const meta = metaQuery.data;
|
||||
const years = useMemo(() => yearsQuery.data ?? [], [yearsQuery.data]);
|
||||
const requestedYear = Number(searchParams.get('jahr'));
|
||||
const year = years.some((y) => y.year === requestedYear)
|
||||
? requestedYear
|
||||
: (years[years.length - 1]?.year ?? null);
|
||||
const view = years.find((y) => y.year === year) ?? null;
|
||||
const legendCounts = useMemo(() => watercraft.legendCounts(view), [watercraft, view]);
|
||||
|
||||
const setYear = useCallback(
|
||||
(value: number) =>
|
||||
setSearchParams(
|
||||
(params) => {
|
||||
params.set('jahr', String(value));
|
||||
return params;
|
||||
},
|
||||
{ replace: true },
|
||||
),
|
||||
[setSearchParams],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing || years.length < 2 || year === null) {
|
||||
return;
|
||||
}
|
||||
const timer = window.setTimeout(() => {
|
||||
const index = years.findIndex((y) => y.year === year);
|
||||
setYear(years[(index + 1) % years.length].year);
|
||||
}, PLAY_INTERVAL_MS);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [playing, years, year, setYear]);
|
||||
|
||||
const dimension = meta?.dimensions.find((d) => d.key === dimensionKey) ?? null;
|
||||
const groups = useMemo(() => (dimension ? buildGroups(dimension) : []), [dimension]);
|
||||
const legendCounts = useMemo(
|
||||
() => (dimension && view ? groupCounts(view.canton.categories[dimension.key], groups) : []),
|
||||
[dimension, view, groups],
|
||||
);
|
||||
|
||||
const handleDimensionChange = useCallback((key: DimensionKey) => {
|
||||
setDimensionKey(key);
|
||||
setHidden(new Set());
|
||||
}, []);
|
||||
|
||||
const handleToggle = useCallback(
|
||||
(label: string) =>
|
||||
setHidden((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(label)) {
|
||||
next.add(label);
|
||||
}
|
||||
return next.size >= groups.length ? new Set() : next;
|
||||
}),
|
||||
[groups.length],
|
||||
);
|
||||
|
||||
const handleShowAll = useCallback(() => setHidden(new Set()), []);
|
||||
const handleClose = useCallback(() => setSelectedName(null), []);
|
||||
const handleSelect = useCallback(
|
||||
(name: string) => setSelectedName((current) => (current === name ? null : name)),
|
||||
|
|
@ -107,8 +41,7 @@ export function WatercraftThurgauPage() {
|
|||
const electric = view && electricIndex >= 0 ? view.canton.categories.fuel[electricIndex] : 0;
|
||||
const unplaced = view?.locations.filter((l) => l.lat === null) ?? [];
|
||||
|
||||
const error = metaQuery.error ?? yearsQuery.error;
|
||||
const loading = metaQuery.isLoading || (meta && meta.years.length === 0) || yearsQuery.isLoading;
|
||||
const { error, loading } = watercraft;
|
||||
|
||||
return (
|
||||
<div className="app with-panel">
|
||||
|
|
@ -153,14 +86,16 @@ export function WatercraftThurgauPage() {
|
|||
</header>
|
||||
|
||||
<main className="map-area">
|
||||
<WatercraftMap
|
||||
locations={view?.locations ?? []}
|
||||
dimension={dimension}
|
||||
groups={groups}
|
||||
hidden={hidden}
|
||||
selectedName={selectedName}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
<MapHost center={THURGAU_LAKE_CENTER}>
|
||||
<WatercraftLayer
|
||||
locations={view?.locations ?? []}
|
||||
dimension={dimension}
|
||||
groups={groups}
|
||||
hidden={hidden}
|
||||
selectedName={selectedName}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
</MapHost>
|
||||
|
||||
{unplaced.length > 0 && (
|
||||
<div className="unplaced">
|
||||
|
|
@ -195,9 +130,9 @@ export function WatercraftThurgauPage() {
|
|||
groups={groups}
|
||||
counts={legendCounts}
|
||||
hidden={hidden}
|
||||
onDimensionChange={handleDimensionChange}
|
||||
onToggle={handleToggle}
|
||||
onShowAll={handleShowAll}
|
||||
onDimensionChange={watercraft.setDimension}
|
||||
onToggle={watercraft.toggleGroup}
|
||||
onShowAll={watercraft.showAllGroups}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -95,7 +95,7 @@ body,
|
|||
min-height: 0;
|
||||
}
|
||||
|
||||
.traffic-map {
|
||||
.map-host {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
|
@ -867,3 +867,215 @@ select {
|
|||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.layer-panel {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
left: 56px;
|
||||
z-index: 800;
|
||||
width: min(380px, calc(100% - 120px));
|
||||
max-height: calc(100% - 170px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: rgba(255, 255, 255, 0.96);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 4px 16px rgba(15, 23, 42, 0.12);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.layer-panel:not(.open) {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
.layer-panel-toggle {
|
||||
border: none;
|
||||
background: none;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.layer-cards {
|
||||
overflow-y: auto;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.layer-card {
|
||||
padding: 8px 12px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.layer-card:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.layer-card-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.layer-card-header label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.layer-card-swatch {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 3px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.layer-card:not(.active) .layer-card-swatch {
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.layer-card-title {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.layer-card-subtitle {
|
||||
display: block;
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.layer-card-link {
|
||||
color: var(--accent);
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.layer-card-note {
|
||||
margin: 6px 0 0;
|
||||
font-size: 11px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.layer-card-body {
|
||||
margin-top: 8px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.layer-card .legend {
|
||||
background: none;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
padding: 0;
|
||||
gap: 6px 12px;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
.layer-card .dimension-tabs {
|
||||
align-self: flex-start;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.layer-card .dimension-tabs button {
|
||||
padding: 0 7px;
|
||||
font-size: 11px;
|
||||
height: 24px;
|
||||
}
|
||||
|
||||
.layer-card .category-chips {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.layer-card .color-scale {
|
||||
justify-content: flex-start;
|
||||
}
|
||||
|
||||
.layer-card .color-scale-steps {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.layer-card .color-scale-step {
|
||||
flex: 1;
|
||||
width: auto;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.layer-card .color-scale-label {
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.unplaced-link {
|
||||
align-self: flex-start;
|
||||
padding: 0;
|
||||
font-size: 11px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.unplaced-link.active {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.context-list {
|
||||
list-style: none;
|
||||
margin: 0 0 8px;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.context-list button {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr;
|
||||
gap: 0 8px;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 6px 10px;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.context-list button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.context-kind {
|
||||
grid-row: span 2;
|
||||
align-self: center;
|
||||
font-size: 10px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.context-name {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.context-value {
|
||||
color: var(--muted);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.overview-hint {
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.layer-panel {
|
||||
max-height: calc(100% - 140px);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
119
client/src/traffic/useTrafficData.ts
Normal file
119
client/src/traffic/useTrafficData.ts
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { fetchDay, fetchMeta, fetchStations } from '../api/traffic';
|
||||
import { SPEEDS } from '../components/TimeControls';
|
||||
import type { FlowAnimator } from './flowAnimator';
|
||||
import { sumCounts } from './vehicleClasses';
|
||||
|
||||
const INITIAL_TIME = 7.5;
|
||||
|
||||
export function useTrafficData() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['meta'],
|
||||
queryFn: fetchMeta,
|
||||
refetchInterval: 10 * 60_000,
|
||||
});
|
||||
const stationsQuery = useQuery({
|
||||
queryKey: ['stations'],
|
||||
queryFn: fetchStations,
|
||||
refetchInterval: (query) =>
|
||||
query.state.data?.some((s) => s.directions.some((d) => d.path.length < 2)) ? 30_000 : false,
|
||||
});
|
||||
|
||||
const dates = useMemo(() => metaQuery.data?.dates ?? [], [metaQuery.data]);
|
||||
const [date, setDate] = useState<string | null>(null);
|
||||
const [time, setTime] = useState(INITIAL_TIME);
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const [hoursPerSecond, setHoursPerSecond] = useState(SPEEDS[1].hoursPerSecond);
|
||||
const animatorRef = useRef<FlowAnimator | null>(null);
|
||||
|
||||
const datesRef = useRef(dates);
|
||||
datesRef.current = dates;
|
||||
const timeRef = useRef(time);
|
||||
timeRef.current = time;
|
||||
const playingRef = useRef(playing);
|
||||
playingRef.current = playing;
|
||||
const speedRef = useRef(hoursPerSecond);
|
||||
speedRef.current = hoursPerSecond;
|
||||
|
||||
useEffect(() => {
|
||||
if (!date && dates.length > 0) {
|
||||
setDate(dates[dates.length - 1]);
|
||||
}
|
||||
}, [date, dates]);
|
||||
|
||||
const dayQuery = useQuery({
|
||||
queryKey: ['day', date],
|
||||
queryFn: () => fetchDay(date!),
|
||||
enabled: !!date,
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
const day = dayQuery.data ?? null;
|
||||
|
||||
const handleAnimatorReady = useCallback((animator: FlowAnimator) => {
|
||||
animatorRef.current = animator;
|
||||
animator.time = timeRef.current;
|
||||
animator.playing = playingRef.current;
|
||||
animator.hoursPerSecond = speedRef.current;
|
||||
animator.onTick = setTime;
|
||||
animator.onDayEnd = () =>
|
||||
setDate((current) => {
|
||||
const all = datesRef.current;
|
||||
const index = current ? all.indexOf(current) : -1;
|
||||
return all.length === 0 ? current : all[(index + 1) % all.length];
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.playing = playing;
|
||||
}
|
||||
}, [playing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.hoursPerSecond = hoursPerSecond;
|
||||
}
|
||||
}, [hoursPerSecond]);
|
||||
|
||||
const handleTimeChange = useCallback((value: number) => {
|
||||
if (animatorRef.current) {
|
||||
animatorRef.current.time = value;
|
||||
}
|
||||
setTime(value);
|
||||
}, []);
|
||||
|
||||
const hour = Math.min(23, Math.floor(time));
|
||||
const stations = useMemo(() => stationsQuery.data ?? [], [stationsQuery.data]);
|
||||
|
||||
const hourTotal = useMemo(
|
||||
() =>
|
||||
day?.stations.reduce(
|
||||
(sum, station) =>
|
||||
sum + station.directions.reduce((s, d) => s + sumCounts(d.hours[hour]), 0),
|
||||
0,
|
||||
) ?? 0,
|
||||
[day, hour],
|
||||
);
|
||||
|
||||
return {
|
||||
meta: metaQuery.data,
|
||||
stations,
|
||||
dates,
|
||||
date,
|
||||
setDate,
|
||||
day,
|
||||
time,
|
||||
hour,
|
||||
hourTotal,
|
||||
playing,
|
||||
setPlaying,
|
||||
hoursPerSecond,
|
||||
setHoursPerSecond,
|
||||
handleTimeChange,
|
||||
handleAnimatorReady,
|
||||
error: metaQuery.error ?? stationsQuery.error ?? dayQuery.error,
|
||||
loading: metaQuery.isLoading || (!!metaQuery.data && dates.length === 0),
|
||||
};
|
||||
}
|
||||
48
client/src/vehicles/useVehicleData.ts
Normal file
48
client/src/vehicles/useVehicleData.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { fetchMunicipalityShapes, fetchVehicleMeta, fetchVehicleYears } from '../api/vehicles';
|
||||
import { buildScale, metricTitle, type Metric } from './metrics';
|
||||
|
||||
export function useVehicleData() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['vehicle-meta'],
|
||||
queryFn: fetchVehicleMeta,
|
||||
refetchInterval: (query) => (query.state.data?.years.length ? false : 15_000),
|
||||
});
|
||||
const ready = !!metaQuery.data?.years.length;
|
||||
const lastRefresh = metaQuery.data?.lastRefresh ?? null;
|
||||
const yearsQuery = useQuery({
|
||||
queryKey: ['vehicle-years', lastRefresh],
|
||||
queryFn: fetchVehicleYears,
|
||||
enabled: ready,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
const shapesQuery = useQuery({
|
||||
queryKey: ['vehicle-shapes', lastRefresh],
|
||||
queryFn: fetchMunicipalityShapes,
|
||||
enabled: ready,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const [metric, setMetric] = useState<Metric>({ kind: 'density', group: 0 });
|
||||
|
||||
const meta = metaQuery.data;
|
||||
const years = useMemo(() => yearsQuery.data ?? [], [yearsQuery.data]);
|
||||
const yearNumbers = useMemo(() => years.map((y) => y.year), [years]);
|
||||
const shapes = useMemo(() => shapesQuery.data ?? [], [shapesQuery.data]);
|
||||
const scale = useMemo(() => buildScale(years, metric), [years, metric]);
|
||||
const title = meta ? metricTitle(metric, meta) : '';
|
||||
|
||||
return {
|
||||
meta,
|
||||
years,
|
||||
yearNumbers,
|
||||
shapes,
|
||||
metric,
|
||||
setMetric,
|
||||
scale,
|
||||
title,
|
||||
error: metaQuery.error ?? yearsQuery.error ?? shapesQuery.error,
|
||||
loading: metaQuery.isLoading || (!!meta && meta.years.length === 0) || yearsQuery.isLoading,
|
||||
};
|
||||
}
|
||||
72
client/src/watercraft/useWatercraftData.ts
Normal file
72
client/src/watercraft/useWatercraftData.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import {
|
||||
fetchWatercraftMeta,
|
||||
fetchWatercraftYears,
|
||||
type DimensionKey,
|
||||
type YearView,
|
||||
} from '../api/watercraft';
|
||||
import { buildGroups, groupCounts } from './categories';
|
||||
|
||||
export function useWatercraftData() {
|
||||
const metaQuery = useQuery({
|
||||
queryKey: ['watercraft-meta'],
|
||||
queryFn: fetchWatercraftMeta,
|
||||
refetchInterval: (query) => (query.state.data?.years.length ? false : 15_000),
|
||||
});
|
||||
const yearsQuery = useQuery({
|
||||
queryKey: ['watercraft-years', metaQuery.data?.lastRefresh ?? null],
|
||||
queryFn: fetchWatercraftYears,
|
||||
enabled: !!metaQuery.data?.years.length,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const [dimensionKey, setDimensionKey] = useState<DimensionKey>('type');
|
||||
const [hidden, setHidden] = useState<Set<string>>(() => new Set());
|
||||
|
||||
const meta = metaQuery.data;
|
||||
const years = useMemo(() => yearsQuery.data ?? [], [yearsQuery.data]);
|
||||
const yearNumbers = useMemo(() => years.map((y) => y.year), [years]);
|
||||
const dimension = meta?.dimensions.find((d) => d.key === dimensionKey) ?? null;
|
||||
const groups = useMemo(() => (dimension ? buildGroups(dimension) : []), [dimension]);
|
||||
|
||||
const setDimension = useCallback((key: DimensionKey) => {
|
||||
setDimensionKey(key);
|
||||
setHidden(new Set());
|
||||
}, []);
|
||||
|
||||
const toggleGroup = useCallback(
|
||||
(label: string) =>
|
||||
setHidden((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(label)) {
|
||||
next.add(label);
|
||||
}
|
||||
return next.size >= groups.length ? new Set() : next;
|
||||
}),
|
||||
[groups.length],
|
||||
);
|
||||
|
||||
const showAllGroups = useCallback(() => setHidden(new Set()), []);
|
||||
|
||||
const legendCounts = useCallback(
|
||||
(view: YearView | null) =>
|
||||
dimension && view ? groupCounts(view.canton.categories[dimension.key], groups) : [],
|
||||
[dimension, groups],
|
||||
);
|
||||
|
||||
return {
|
||||
meta,
|
||||
years,
|
||||
yearNumbers,
|
||||
dimension,
|
||||
groups,
|
||||
hidden,
|
||||
setDimension,
|
||||
toggleGroup,
|
||||
showAllGroups,
|
||||
legendCounts,
|
||||
error: metaQuery.error ?? yearsQuery.error,
|
||||
loading: metaQuery.isLoading || (!!meta && meta.years.length === 0) || yearsQuery.isLoading,
|
||||
};
|
||||
}
|
||||
|
|
@ -78,4 +78,20 @@ sequenceDiagram
|
|||
| [Gemeindegrenzen](datasets/gemeindegrenzen.md) | swisstopo swissBOUNDARIES3D | swisstopo OGD | Feature pro BFS-Nummer (WGS84) | einmal pro Gemeinde; neu bei geänderter `OutlinesFileName` | `vehicles/thurgau/outlines-v1.json` |
|
||||
| [Grundkarten](datasets/grundkarten.md) | swisstopo WMTS (`pixelkarte-grau/-farbe`, `swissimage`) | swisstopo OGD | Kacheln direkt vom Browser | nie gecacht vom Server | – |
|
||||
|
||||
## Kombinierte Karte
|
||||
|
||||
Die Seite `/karte/thurgau` zeigt Fahrzeugbestand, Wasserfahrzeuge und Strassenverkehr als Ebenen auf einer Karte. Sie lädt keine eigenen Daten, sondern ruft dieselben Endpunkte wie die Einzelkarten auf (`/api/vehicles`, `/api/watercraft`, `/api/traffic`); Quellen, Abruf, Aktualisierung und Cache sind also die der Datensätze oben.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
v["/api/vehicles<br/>Gemeinden pro Jahr"] --> page
|
||||
w["/api/watercraft<br/>Bootsstandorte pro Jahr"] --> page
|
||||
t["/api/traffic<br/>Zählstellen pro Stunde"] --> page
|
||||
page["Kombinierte Karte<br/>/karte/thurgau"] --> assign["Zuordnung im Browser:<br/>Zählstelle in Gemeindegrenze,<br/>Bootsstandort zur nächsten Gemeinde"]
|
||||
```
|
||||
|
||||
- Die Ebenen stehen in der URL (`?ebenen=fahrzeuge,boote,verkehr&jahr=2025`); ohne `ebenen` sind alle eingeschaltet.
|
||||
- Das Jahr gilt für Fahrzeugbestand (ab 2023) und Wasserfahrzeuge (ab 2021). Ist eine Ebene für das gewählte Jahr leer, zeigt die Ebene einen Hinweis. Die Verkehrszählungen haben kein Jahr, sondern Tag und Stunde aus dem Verkehrs-Cache.
|
||||
- „In dieser Gemeinde“ ordnet Zählstellen über die Gemeindegrenze zu (bis 250 m daneben) und Bootsstandorte der nächsten Gemeinde bis 1,5 km, weil die Uferpunkte im See und damit ausserhalb der Grenzen liegen.
|
||||
|
||||
Alle Intervalle und Pfade sind in `appsettings.json` unter `Traffic`, `Watercraft` und `Vehicles` konfigurierbar (`DataPath`, `RefreshInterval`). Die Quellenangaben, die die Lizenzen verlangen, stehen in der Fusszeile jeder Karte. Details, Ablaufdiagramm und Besonderheiten stehen in der Datei des jeweiligen Datensatzes.
|
||||
|
|
|
|||
Loading…
Reference in a new issue