OpenDataVisualizer/Schaad.OpenData.Traffic/Geometry/SwisstopoClient.cs
Claudio Schaad 8de869b023 Fix roundabout arm geometry for untargetable directions
Stations like "WEINFELDEN Kreisel West - Umfahrung" have directions
such as "zur Umfahrung" or "von Egelseestrasse" that cannot be
geocoded, so their dots were drawn on a nearby side road or around
the roundabout ring.

- Derive the roundabout centre from all stations sharing the name
  before " - " and point each arm outward from it
- Prefer road segments named like the station's address when
  following an arm; reject arms that don't get away from the centre
- Parse "zur", "zum", "Richtung" and "vom" direction prefixes
- Treat only swissTLM3D object kinds 12-19 as non-roads; kind 20 is
  a regular road (e.g. Dunantstrasse in Weinfelden)
- Bump the geometry cache to v7 so all stations are rebuilt

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

145 lines
6.1 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 FirstNonRoadObjectKind = 12;
private const int LastNonRoadObjectKind = 19;
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() is < FirstNonRoadObjectKind or > LastNonRoadObjectKind;
var name = hasProperties && properties.TryGetProperty("strassenname", out var streetName) && streetName.ValueKind == JsonValueKind.String
? streetName.GetString()
: null;
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,
name));
}
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();
}