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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-11-06 20:17:26 +00:00

77 lines
2.7 KiB
C#

using System.Globalization;
using System.Text.RegularExpressions;
using Schaad.OpenData.Traffic.Models;
namespace Schaad.OpenData.Traffic.Source;
public static partial class ThurgauTrafficMapper
{
public static TrafficImport Map(IEnumerable<ThurgauTrafficRecord> records)
{
var counts = new List<HourlyCount>();
var firstRecords = new Dictionary<int, ThurgauTrafficRecord>();
var directions = new Dictionary<int, Dictionary<string, string>>();
foreach (var record in records)
{
if (record.Coordinates is null || !TryParseDate(record.Date, out var date) || record.Hour is < 0 or > 23)
{
continue;
}
firstRecords.TryAdd(record.Code, record);
if (!directions.TryGetValue(record.Code, out var stationDirections))
{
stationDirections = new Dictionary<string, string>(StringComparer.Ordinal);
directions[record.Code] = stationDirections;
}
var direction = Clean(record.Direction);
if (!stationDirections.TryGetValue(direction, out var pooled))
{
pooled = direction;
stationDirections[direction] = pooled;
}
counts.Add(new HourlyCount(record.Code, pooled, date, record.Hour, ToCounts(record)));
}
var stations = firstRecords.Values
.Select(r => new Station(
r.Code,
Clean(r.Name),
Clean(r.Municipality),
Clean(r.Address),
Clean(r.Road),
new GeoPoint(r.Coordinates!.Lat, r.Coordinates.Lon),
[.. directions[r.Code].Keys.Order(StringComparer.Ordinal)]))
.OrderBy(s => s.Code)
.ToList();
return new TrafficImport(stations, counts);
}
private static VehicleCounts ToCounts(ThurgauTrafficRecord record) => new(
record.Bus ?? 0,
record.Motorcycle ?? 0,
record.Car ?? 0,
record.CarWithTrailer ?? 0,
record.Van ?? 0,
record.VanWithTrailer ?? 0,
record.VanWithSemiTrailer ?? 0,
record.Truck ?? 0,
record.TruckWithTrailer ?? 0,
record.SemiTrailerTruck ?? 0);
private static bool TryParseDate(string? value, out DateOnly date)
{
date = default;
return value is { Length: >= 10 }
&& DateOnly.TryParseExact(value[..10], "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
private static string Clean(string? value) => MultipleSpaces().Replace(value ?? "", " ").Trim();
[GeneratedRegex(@"\s+")]
private static partial Regex MultipleSpaces();
}