using Schaad.OpenData.Traffic.Models; namespace Schaad.OpenData.Traffic.Geometry; public class StationGeometryService(SwisstopoClient swisstopoClient) { private const double HalfPathLengthMeters = 300; private const double SearchRadiusMeters = 650; private const double MetersPerDegreeLat = 111_320; private const double MinimumArmOffsetMeters = 3; private const double OutwardTargetMeters = 3000; private const string RoundaboutMarker = "Kreisel"; public virtual async Task BuildAsync(Station station, IReadOnlyList stations, CancellationToken cancellationToken) { var isRoundaboutArm = station.Name.Contains(RoundaboutMarker, StringComparison.OrdinalIgnoreCase); var outwardTarget = isRoundaboutArm ? OutwardTarget(station, stations) : null; var directions = new List(); foreach (var direction in station.Directions) { var target = DirectionTarget.Parse(direction); var location = outwardTarget ?? await FindPlaceAsync(target.Place, station.Location, cancellationToken); directions.Add(new ResolvedDirection(direction, target, location)); } var targetLocation = directions.Select(d => d.TargetLocation).FirstOrDefault(l => l is not null); var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken); var roadPath = (isRoundaboutArm && targetLocation is { } armTarget ? RoadPathBuilder.BuildArmPath(station.Location, segments, armTarget, 2 * HalfPathLengthMeters, station.Address) : null) ?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters); var path = roadPath ?? RoadPathBuilder.BuildStraightPath(station.Location, targetLocation, HalfPathLengthMeters); return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions)); } internal static GeoPoint? OutwardTarget(Station station, IReadOnlyList stations) { var key = RoundaboutKey(station.Name); var siblings = stations.Where(s => RoundaboutKey(s.Name) == key).ToList(); if (siblings.Count < 2) { return null; } var center = new GeoPoint(siblings.Average(s => s.Location.Lat), siblings.Average(s => s.Location.Lon)); var deltaLat = station.Location.Lat - center.Lat; var deltaLon = station.Location.Lon - center.Lon; var meters = Math.Sqrt( Math.Pow(deltaLat * MetersPerDegreeLat, 2) + Math.Pow(deltaLon * MetersPerDegreeLat * Math.Cos(center.Lat * Math.PI / 180), 2)); if (meters < MinimumArmOffsetMeters) { return null; } var scale = OutwardTargetMeters / meters; return new GeoPoint(center.Lat + deltaLat * scale, center.Lon + deltaLon * scale); } private static string RoundaboutKey(string name) => name.Split(" - ", 2)[0].Trim(); private async Task FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken) { foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)) { if (await swisstopoClient.FindPlaceAsync(part, near, cancellationToken) is { } location) { return location; } } return null; } }