OpenDataVisualizer/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs
Claudio Schaad e729ea3403 Add Thurgau traffic visualizer with animated map
ASP.NET Core 10 API and React client that visualize the canton of
Thurgau's hourly traffic counts by vehicle class (data.tg.ch, CC0).

- Background refresh from data.tg.ch every 6 h into a per-day JSON
  cache, so history grows beyond the source's two-week window
- Road geometry per station direction from swisstopo swissTLM3D,
  oriented by geocoding the direction's target town; roundabout arms
  follow the road outward only
- Leaflet map with canvas animation: dots drive along the road in
  both directions, density by hourly count, colour by vehicle class,
  right-hand traffic; play/pause, time slider and day selection
- Station panel with per-class counts and Chart.js charts (hourly,
  weekday/weekend profile, daily totals, class mix)
- swisstopo base map switcher (grey, colour, aerial)
- Dockerfile and docker-compose with a data volume
- xUnit tests for mapping, cache, geometry, geocoding and analysis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 20:33:58 +01:00

140 lines
5.8 KiB
C#

using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.RegularExpressions;
using Schaad.OpenData.Traffic.Models;
namespace Schaad.OpenData.Traffic.Geometry;
public partial class SwisstopoClient(HttpClient httpClient)
{
private const double MetersPerDegreeLat = 111_320;
private const int NoTrafficImportance = 999998;
private const int MaxRetries = 2;
private const int PageSize = 200;
private const int MaxPages = 5;
private const int MaxDrivableObjectKind = 11;
public virtual async Task<IReadOnlyList<RoadSegment>> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken)
{
var deltaLat = radiusMeters / MetersPerDegreeLat;
var deltaLon = radiusMeters / (MetersPerDegreeLat * Math.Cos(center.Lat * Math.PI / 180));
var envelope = string.Join(',', new[]
{
center.Lon - deltaLon,
center.Lat - deltaLat,
center.Lon + deltaLon,
center.Lat + deltaLat,
}.Select(v => v.ToString("F6", CultureInfo.InvariantCulture)));
var baseUrl = "MapServer/identify?geometryType=esriGeometryEnvelope"
+ $"&geometry={envelope}&mapExtent={envelope}&sr=4326&imageDisplay=1000,1000,96&tolerance=0"
+ $"&layers=all:ch.swisstopo.swisstlm3d-strassen&returnGeometry=true&geometryFormat=geojson&limit={PageSize}";
var segments = new List<RoadSegment>();
for (var page = 0; page < MaxPages; page++)
{
using var document = await GetJsonAsync($"{baseUrl}&offset={page * PageSize}", cancellationToken);
var features = document.RootElement.GetProperty("results").EnumerateArray().ToList();
segments.AddRange(features.SelectMany(ToSegments));
if (features.Count < PageSize)
{
break;
}
}
return segments;
}
private static IEnumerable<RoadSegment> ToSegments(JsonElement feature)
{
if (!feature.TryGetProperty("geometry", out var geometry))
{
return [];
}
var hasProperties = feature.TryGetProperty("properties", out var properties);
var isMainRoad = hasProperties
&& properties.TryGetProperty("verkehrsbedeutung", out var importance)
&& importance.ValueKind == JsonValueKind.Number
&& importance.GetInt32() != NoTrafficImportance;
var isDrivable = !hasProperties
|| !properties.TryGetProperty("objektart", out var kind)
|| kind.ValueKind != JsonValueKind.Number
|| kind.GetInt32() <= MaxDrivableObjectKind;
var coordinates = geometry.GetProperty("coordinates");
var parts = geometry.GetProperty("type").GetString() switch
{
"LineString" => [coordinates],
"MultiLineString" => coordinates.EnumerateArray().ToList(),
_ => new List<JsonElement>(),
};
return parts.Select(part => new RoadSegment(
part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(),
isMainRoad,
isDrivable));
}
public virtual async Task<GeoPoint?> FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken)
{
var url = $"SearchServer?type=locations&origins=gg25,gazetteer&limit=15&searchText={Uri.EscapeDataString(name)}";
using var document = await GetJsonAsync(url, cancellationToken);
var normalizedName = Normalize(name);
var candidates = document.RootElement.GetProperty("results").EnumerateArray()
.Select(r => r.GetProperty("attrs"))
.Where(a => a.TryGetProperty("lat", out _) && a.TryGetProperty("lon", out _))
.Select(a => (
Label: HtmlTags().Replace(a.GetProperty("label").GetString() ?? "", ""),
Location: new GeoPoint(a.GetProperty("lat").GetDouble(), a.GetProperty("lon").GetDouble())))
.Where(c => Normalize(c.Label).Contains(normalizedName, StringComparison.Ordinal))
.ToList();
if (candidates.Count == 0)
{
return null;
}
return candidates.MinBy(c => DistanceSquared(c.Location, near)).Location;
}
private async Task<JsonDocument> GetJsonAsync(string url, CancellationToken cancellationToken)
{
var response = await httpClient.GetAsync(url, cancellationToken);
for (var attempt = 1; attempt <= MaxRetries && IsTransient(response.StatusCode); attempt++)
{
response.Dispose();
await Task.Delay(TimeSpan.FromSeconds(2 * attempt), cancellationToken);
response = await httpClient.GetAsync(url, cancellationToken);
}
using var _ = response;
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
}
private static bool IsTransient(HttpStatusCode statusCode) =>
statusCode is HttpStatusCode.TooManyRequests || (int)statusCode >= 500;
private static double DistanceSquared(GeoPoint a, GeoPoint b)
{
var dLat = a.Lat - b.Lat;
var dLon = (a.Lon - b.Lon) * Math.Cos(a.Lat * Math.PI / 180);
return dLat * dLat + dLon * dLon;
}
internal static string Normalize(string value) => value
.ToLowerInvariant()
.Replace("ä", "ae", StringComparison.Ordinal)
.Replace("ö", "oe", StringComparison.Ordinal)
.Replace("ü", "ue", StringComparison.Ordinal)
.Replace("é", "e", StringComparison.Ordinal)
.Replace("è", "e", StringComparison.Ordinal)
.Replace(".", "", StringComparison.Ordinal)
.Replace(" ", "", StringComparison.Ordinal);
[GeneratedRegex("<[^>]+>")]
private static partial Regex HtmlTags();
}