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> 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(); 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 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(), }; 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 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 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(); }