Add Thurgau traffic visualizer and start page #1
11 changed files with 165 additions and 37 deletions
|
|
@ -56,11 +56,11 @@ The cache accumulates history beyond the source's two-week window; refreshes onl
|
||||||
|
|
||||||
The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction:
|
The source has one point per station and directions as text (`nach X`, `von X`, or just `X`). `StationGeometryService` turns that into a road polyline per direction, oriented in driving direction:
|
||||||
|
|
||||||
1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200). `verkehrsbedeutung != 999998` marks main roads, `objektart <= 11` drivable roads (higher values are paths and lane markings).
|
1. `SwisstopoClient.GetRoadSegmentsAsync` loads swissTLM3D road segments around the station (api3.geo.admin.ch identify, paged by 200) with their street name. `verkehrsbedeutung != 999998` marks main roads; `objektart` 12–19 are paths and lane markings (15/16 seen in practice), everything else is a road — note that 20 is a regular road type.
|
||||||
2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m.
|
2. `RoadPathBuilder.BuildRoadPath` snaps to a main road within 60 m (else the nearest drivable road), stitches connected segments (≤ 60° turn, penalty for changing road class) and trims to ±300 m.
|
||||||
3. Stations named `… Kreisel …` sit on a roundabout arm: `BuildArmPath` follows every road segment within 80 m outward (600 m) and keeps the one that gets furthest toward the target town (a roundabout ring loops back and loses); it falls back to `BuildRoadPath`.
|
3. Stations named `… Kreisel …` sit on a roundabout arm. The roundabout centre is the average position of all stations sharing the name part before ` - ` (e.g. the four `WEINFELDEN Kreisel West` stations), and the arm target is a point 3 km outward from that centre through the station (`StationGeometryService.OutwardTarget`), so no geocoding is needed. `BuildArmPath` follows every segment within 80 m outward for 600 m, preferring segments named like the station's address (the arm's street), and keeps the arm that gets furthest outward; a ring loops back and is rejected. A roundabout with a single station falls back to the geocoded target.
|
||||||
4. `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes.
|
4. Otherwise `SwisstopoClient.FindPlaceAsync` geocodes the target town (SearchServer, municipalities + gazetteer, label must contain the name with ä→ae etc., nearest candidate wins — "Landquart" is also a place in Arbon). Names with `/` are split, since the SearchServer returns 503 for slashes. Directions can be `nach`/`zur`/`zum`/`Richtung X` (toward) or `von`/`vom X` (from); targets like `Umfahrung`, `Zentrum` or street names cannot be geocoded.
|
||||||
5. `RoadPathBuilder.Orient` points each direction toward (`nach`) or away from (`von`) its target; the two directions of a station are always opposite.
|
5. `RoadPathBuilder.Orient` points each direction toward or away from its target; the two directions of a station are always opposite.
|
||||||
|
|
||||||
When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt.
|
When the geometry algorithm changes, bump `GeometryFileName` in `TrafficCacheStorage` so all stations are rebuilt.
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -16,6 +16,12 @@ public class DirectionTargetTestShould
|
||||||
DirectionTarget.Parse("von Frauenfeld").ShouldBe(new DirectionTarget("Frauenfeld", false));
|
DirectionTarget.Parse("von Frauenfeld").ShouldBe(new DirectionTarget("Frauenfeld", false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ParseDestinationWhenDirectionStartsWithZur()
|
||||||
|
{
|
||||||
|
DirectionTarget.Parse("zur Umfahrung").ShouldBe(new DirectionTarget("Umfahrung", true));
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix()
|
public void TreatPlainNameAsDestinationWhenDirectionHasNoPrefix()
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -21,18 +21,74 @@ public class StationGeometryServiceTestShould
|
||||||
swisstopoClient.FindPlaceAsync("Wilen", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>()).Returns((GeoPoint?)null);
|
swisstopoClient.FindPlaceAsync("Wilen", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>()).Returns((GeoPoint?)null);
|
||||||
swisstopoClient.FindPlaceAsync("Busswil", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>()).Returns(TestData.Meters(0, 2000));
|
swisstopoClient.FindPlaceAsync("Busswil", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>()).Returns(TestData.Meters(0, 2000));
|
||||||
|
|
||||||
var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), CancellationToken.None);
|
var geometry = await service.BuildAsync(TestData.Station(413, "Wilen/Busswil", "Gloten"), [], CancellationToken.None);
|
||||||
|
|
||||||
await swisstopoClient.DidNotReceive().FindPlaceAsync("Wilen/Busswil", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>());
|
await swisstopoClient.DidNotReceive().FindPlaceAsync("Wilen/Busswil", Arg.Any<GeoPoint>(), Arg.Any<CancellationToken>());
|
||||||
geometry.Directions[0].Path[^1].Lat.ShouldBeGreaterThan(TestData.Origin.Lat);
|
geometry.Directions[0].Path[^1].Lat.ShouldBeGreaterThan(TestData.Origin.Lat);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static Station Arm(int code, string name, (double East, double North) offset, string address, params string[] directions) =>
|
||||||
|
TestData.Station(code, directions) with
|
||||||
|
{
|
||||||
|
Name = name,
|
||||||
|
Address = address,
|
||||||
|
Location = TestData.Meters(offset.East, offset.North),
|
||||||
|
};
|
||||||
|
|
||||||
|
private static Station[] KreiselWest() =>
|
||||||
|
[
|
||||||
|
Arm(1, "WEINFELDEN Kreisel West - Weinfelden", (30, 0), "Frauenfelderstrasse", "nach Weinfelden", "von Weinfelden"),
|
||||||
|
Arm(2, "WEINFELDEN Kreisel West - Umfahrung", (0, -30), "Dunantstrasse", "von Umfahrung", "zur Umfahrung"),
|
||||||
|
Arm(3, "WEINFELDEN Kreisel West - Märstetten", (-30, 0), "Frauenfelderstrasse", "nach Maerstetten", "von Maerstetten"),
|
||||||
|
Arm(4, "WEINFELDEN Kreisel West - Egelseestrasse", (0, 30), "Egelseestrasse", "von Egelseestrasse", "zur Egelseestrasse"),
|
||||||
|
];
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PointAwayFromRoundaboutCenterWhenComputingOutwardTarget()
|
||||||
|
{
|
||||||
|
var stations = KreiselWest();
|
||||||
|
|
||||||
|
var target = StationGeometryService.OutwardTarget(stations[1], stations)!.Value;
|
||||||
|
|
||||||
|
target.Lat.ShouldBeLessThan(TestData.Meters(0, -2900).Lat);
|
||||||
|
target.Lon.ShouldBe(TestData.Origin.Lon, 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void ReturnNoOutwardTargetWhenRoundaboutHasSingleStation()
|
||||||
|
{
|
||||||
|
var station = KreiselWest()[0];
|
||||||
|
|
||||||
|
StationGeometryService.OutwardTarget(station, [station]).ShouldBeNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task FollowArmNamedLikeStationAddressWhenTargetIsNotAPlace()
|
||||||
|
{
|
||||||
|
var stations = KreiselWest();
|
||||||
|
swisstopoClient.GetRoadSegmentsAsync(default, default, default).ReturnsForAnyArgs(
|
||||||
|
[
|
||||||
|
new RoadSegment([TestData.Meters(0, -28), TestData.Meters(-80, 60)], true, true, null),
|
||||||
|
new RoadSegment([TestData.Meters(0, -10), TestData.Meters(0, -200)], true, true, "Dunantstrasse"),
|
||||||
|
new RoadSegment([TestData.Meters(0, -200), TestData.Meters(0, -700)], true, true, "Dunantstrasse"),
|
||||||
|
]);
|
||||||
|
|
||||||
|
var geometry = await service.BuildAsync(stations[1], stations, CancellationToken.None);
|
||||||
|
|
||||||
|
await swisstopoClient.DidNotReceiveWithAnyArgs().FindPlaceAsync(default!, default, default);
|
||||||
|
var outward = geometry.Directions.Single(d => d.Direction == "zur Umfahrung").Path;
|
||||||
|
var inward = geometry.Directions.Single(d => d.Direction == "von Umfahrung").Path;
|
||||||
|
outward[^1].Lat.ShouldBeLessThan(outward[0].Lat);
|
||||||
|
outward[^1].Lon.ShouldBe(TestData.Origin.Lon, 1e-6);
|
||||||
|
inward[^1].ShouldBe(outward[0]);
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task UseStraightPathWhenNoRoadIsFound()
|
public async Task UseStraightPathWhenNoRoadIsFound()
|
||||||
{
|
{
|
||||||
swisstopoClient.FindPlaceAsync(default!, default, default).ReturnsForAnyArgs(TestData.Meters(1000, 0));
|
swisstopoClient.FindPlaceAsync(default!, default, default).ReturnsForAnyArgs(TestData.Meters(1000, 0));
|
||||||
|
|
||||||
var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), CancellationToken.None);
|
var geometry = await service.BuildAsync(TestData.Station(1, "nach A", "von A"), [], CancellationToken.None);
|
||||||
|
|
||||||
geometry.FollowsRoad.ShouldBeFalse();
|
geometry.FollowsRoad.ShouldBeFalse();
|
||||||
geometry.Directions.Count.ShouldBe(2);
|
geometry.Directions.Count.ShouldBe(2);
|
||||||
|
|
|
||||||
|
|
@ -97,15 +97,17 @@ public class SwisstopoClientTestShould
|
||||||
{
|
{
|
||||||
var body = """
|
var body = """
|
||||||
{"results":[
|
{"results":[
|
||||||
{"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9}},
|
{"geometry":{"type":"LineString","coordinates":[[9.1,47.5],[9.2,47.5]]},"properties":{"objektart":9,"strassenname":"Dunantstrasse"}},
|
||||||
{"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}}
|
{"geometry":{"type":"LineString","coordinates":[[9.1,47.6],[9.2,47.6]]},"properties":{"objektart":15}},
|
||||||
|
{"geometry":{"type":"LineString","coordinates":[[9.1,47.7],[9.2,47.7]]},"properties":{"objektart":20}}
|
||||||
]}
|
]}
|
||||||
""";
|
""";
|
||||||
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
|
var client = Client(new StubHandler((HttpStatusCode.OK, body)));
|
||||||
|
|
||||||
var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None);
|
var segments = await client.GetRoadSegmentsAsync(new GeoPoint(47.5, 9.15), 300, CancellationToken.None);
|
||||||
|
|
||||||
segments.Select(s => s.IsDrivable).ShouldBe([true, false]);
|
segments.Select(s => s.IsDrivable).ShouldBe([true, false, true]);
|
||||||
|
segments.Select(s => s.Name).ShouldBe(["Dunantstrasse", null, null]);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|
|
||||||
|
|
@ -2,17 +2,26 @@ namespace Schaad.OpenData.Traffic.Geometry;
|
||||||
|
|
||||||
public sealed record DirectionTarget(string Place, bool IsDestination)
|
public sealed record DirectionTarget(string Place, bool IsDestination)
|
||||||
{
|
{
|
||||||
|
private static readonly string[] DestinationPrefixes = ["nach ", "zur ", "zum ", "richtung "];
|
||||||
|
private static readonly string[] OriginPrefixes = ["von ", "vom "];
|
||||||
|
|
||||||
public static DirectionTarget Parse(string direction)
|
public static DirectionTarget Parse(string direction)
|
||||||
{
|
{
|
||||||
var text = direction.Trim();
|
var text = direction.Trim();
|
||||||
if (text.StartsWith("nach ", StringComparison.OrdinalIgnoreCase))
|
foreach (var prefix in OriginPrefixes)
|
||||||
{
|
{
|
||||||
return new DirectionTarget(text[5..].Trim(), true);
|
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return new DirectionTarget(text[prefix.Length..].Trim(), false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (text.StartsWith("von ", StringComparison.OrdinalIgnoreCase))
|
foreach (var prefix in DestinationPrefixes)
|
||||||
{
|
{
|
||||||
return new DirectionTarget(text[4..].Trim(), false);
|
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
return new DirectionTarget(text[prefix.Length..].Trim(), true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new DirectionTarget(text, true);
|
return new DirectionTarget(text, true);
|
||||||
|
|
|
||||||
|
|
@ -13,15 +13,16 @@ public static class RoadPathBuilder
|
||||||
|
|
||||||
private const double ArmSearchMeters = 80;
|
private const double ArmSearchMeters = 80;
|
||||||
private const float ArmDistancePenalty = 2f;
|
private const float ArmDistancePenalty = 2f;
|
||||||
|
private const float MinimumArmProgressMeters = 30f;
|
||||||
|
|
||||||
private sealed record RoadLine(List<Vector2> Points, bool IsMainRoad);
|
private sealed record RoadLine(List<Vector2> Points, bool IsMainRoad, string? Name);
|
||||||
|
|
||||||
private static List<RoadLine> ToLines(IReadOnlyList<RoadSegment> segments, LocalProjection projection)
|
private static List<RoadLine> ToLines(IReadOnlyList<RoadSegment> segments, LocalProjection projection)
|
||||||
{
|
{
|
||||||
var usable = segments.Where(s => s.Points.Count >= 2).ToList();
|
var usable = segments.Where(s => s.Points.Count >= 2).ToList();
|
||||||
var drivable = usable.Where(s => s.IsDrivable).ToList();
|
var drivable = usable.Where(s => s.IsDrivable).ToList();
|
||||||
return (drivable.Count > 0 ? drivable : usable)
|
return (drivable.Count > 0 ? drivable : usable)
|
||||||
.Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad))
|
.Select(s => new RoadLine(s.Points.Select(projection.ToLocal).ToList(), s.IsMainRoad, s.Name))
|
||||||
.ToList();
|
.ToList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -54,7 +55,12 @@ public static class RoadPathBuilder
|
||||||
return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null;
|
return trimmed.Count >= 2 ? trimmed.Select(projection.ToGeo).ToList() : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static IReadOnlyList<GeoPoint>? BuildArmPath(GeoPoint station, IReadOnlyList<RoadSegment> segments, GeoPoint target, double lengthMeters)
|
public static IReadOnlyList<GeoPoint>? BuildArmPath(
|
||||||
|
GeoPoint station,
|
||||||
|
IReadOnlyList<RoadSegment> segments,
|
||||||
|
GeoPoint target,
|
||||||
|
double lengthMeters,
|
||||||
|
string? roadName = null)
|
||||||
{
|
{
|
||||||
var projection = new LocalProjection(station);
|
var projection = new LocalProjection(station);
|
||||||
var toward = projection.ToLocal(target);
|
var toward = projection.ToLocal(target);
|
||||||
|
|
@ -65,22 +71,33 @@ public static class RoadPathBuilder
|
||||||
|
|
||||||
toward = Vector2.Normalize(toward);
|
toward = Vector2.Normalize(toward);
|
||||||
var lines = ToLines(segments, projection);
|
var lines = ToLines(segments, projection);
|
||||||
var best = lines
|
var nearby = lines
|
||||||
.Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points)))
|
.Select((line, index) => (Index: index, Distance: DistanceToPolyline(Vector2.Zero, line.Points), line.Name))
|
||||||
.Where(c => c.Distance <= ArmSearchMeters)
|
.Where(c => c.Distance <= ArmSearchMeters)
|
||||||
|
.ToList();
|
||||||
|
var named = nearby
|
||||||
|
.Where(c => !string.IsNullOrEmpty(roadName) && string.Equals(c.Name, roadName, StringComparison.OrdinalIgnoreCase))
|
||||||
|
.Select(c => (c.Index, c.Distance))
|
||||||
|
.ToList();
|
||||||
|
var all = nearby.Select(c => (c.Index, c.Distance)).ToList();
|
||||||
|
|
||||||
|
var arm = BestArm(lines, named, toward, lengthMeters) ?? BestArm(lines, all, toward, lengthMeters);
|
||||||
|
return arm?.Select(projection.ToGeo).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<Vector2>? BestArm(List<RoadLine> lines, List<(int Index, double Distance)> candidates, Vector2 toward, double lengthMeters) =>
|
||||||
|
candidates
|
||||||
.Select(c =>
|
.Select(c =>
|
||||||
{
|
{
|
||||||
var arm = FollowArm(lines, c.Index, toward, lengthMeters);
|
var arm = FollowArm(lines, c.Index, toward, lengthMeters);
|
||||||
var progress = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters ? Vector2.Dot(arm[^1], toward) : float.MinValue;
|
var isValid = arm.Count >= 2 && Length(arm) >= MinimumSideLengthMeters && Vector2.Dot(arm[^1], toward) >= MinimumArmProgressMeters;
|
||||||
return (Arm: arm, Score: progress - ArmDistancePenalty * c.Distance);
|
return (Arm: arm, IsValid: isValid, Score: Vector2.Dot(arm.Count > 0 ? arm[^1] : Vector2.Zero, toward) - ArmDistancePenalty * c.Distance);
|
||||||
})
|
})
|
||||||
.Where(c => c.Score > float.MinValue / 2)
|
.Where(c => c.IsValid)
|
||||||
.OrderByDescending(c => c.Score)
|
.OrderByDescending(c => c.Score)
|
||||||
|
.Select(c => c.Arm)
|
||||||
.FirstOrDefault();
|
.FirstOrDefault();
|
||||||
|
|
||||||
return best.Arm?.Select(projection.ToGeo).ToList();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static List<Vector2> FollowArm(List<RoadLine> lines, int start, Vector2 toward, double lengthMeters)
|
private static List<Vector2> FollowArm(List<RoadLine> lines, int start, Vector2 toward, double lengthMeters)
|
||||||
{
|
{
|
||||||
var chain = new List<Vector2>(lines[start].Points);
|
var chain = new List<Vector2>(lines[start].Points);
|
||||||
|
|
|
||||||
|
|
@ -2,4 +2,4 @@ using Schaad.OpenData.Traffic.Models;
|
||||||
|
|
||||||
namespace Schaad.OpenData.Traffic.Geometry;
|
namespace Schaad.OpenData.Traffic.Geometry;
|
||||||
|
|
||||||
public sealed record RoadSegment(IReadOnlyList<GeoPoint> Points, bool IsMainRoad, bool IsDrivable = true);
|
public sealed record RoadSegment(IReadOnlyList<GeoPoint> Points, bool IsMainRoad, bool IsDrivable = true, string? Name = null);
|
||||||
|
|
|
||||||
|
|
@ -6,22 +6,28 @@ public class StationGeometryService(SwisstopoClient swisstopoClient)
|
||||||
{
|
{
|
||||||
private const double HalfPathLengthMeters = 300;
|
private const double HalfPathLengthMeters = 300;
|
||||||
private const double SearchRadiusMeters = 650;
|
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<StationGeometry> BuildAsync(Station station, CancellationToken cancellationToken)
|
public virtual async Task<StationGeometry> BuildAsync(Station station, IReadOnlyList<Station> stations, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
var isRoundaboutArm = station.Name.Contains(RoundaboutMarker, StringComparison.OrdinalIgnoreCase);
|
||||||
|
var outwardTarget = isRoundaboutArm ? OutwardTarget(station, stations) : null;
|
||||||
|
|
||||||
var directions = new List<ResolvedDirection>();
|
var directions = new List<ResolvedDirection>();
|
||||||
foreach (var direction in station.Directions)
|
foreach (var direction in station.Directions)
|
||||||
{
|
{
|
||||||
var target = DirectionTarget.Parse(direction);
|
var target = DirectionTarget.Parse(direction);
|
||||||
directions.Add(new ResolvedDirection(direction, target, await FindPlaceAsync(target.Place, station.Location, cancellationToken)));
|
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 targetLocation = directions.Select(d => d.TargetLocation).FirstOrDefault(l => l is not null);
|
||||||
var isRoundaboutArm = station.Name.Contains("Kreisel", StringComparison.OrdinalIgnoreCase) && targetLocation is not null;
|
|
||||||
|
|
||||||
var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken);
|
var segments = await swisstopoClient.GetRoadSegmentsAsync(station.Location, SearchRadiusMeters, cancellationToken);
|
||||||
var roadPath = (isRoundaboutArm
|
var roadPath = (isRoundaboutArm && targetLocation is { } armTarget
|
||||||
? RoadPathBuilder.BuildArmPath(station.Location, segments, targetLocation!.Value, 2 * HalfPathLengthMeters)
|
? RoadPathBuilder.BuildArmPath(station.Location, segments, armTarget, 2 * HalfPathLengthMeters, station.Address)
|
||||||
: null)
|
: null)
|
||||||
?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters);
|
?? RoadPathBuilder.BuildRoadPath(station.Location, segments, HalfPathLengthMeters);
|
||||||
|
|
||||||
|
|
@ -30,6 +36,32 @@ public class StationGeometryService(SwisstopoClient swisstopoClient)
|
||||||
return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions));
|
return new StationGeometry(station.Code, roadPath is not null, RoadPathBuilder.Orient(station.Location, path, directions));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal static GeoPoint? OutwardTarget(Station station, IReadOnlyList<Station> 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<GeoPoint?> FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken)
|
private async Task<GeoPoint?> FindPlaceAsync(string place, GeoPoint near, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
foreach (var part in place.Split('/', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
|
|
||||||
|
|
@ -13,7 +13,8 @@ public partial class SwisstopoClient(HttpClient httpClient)
|
||||||
private const int MaxRetries = 2;
|
private const int MaxRetries = 2;
|
||||||
private const int PageSize = 200;
|
private const int PageSize = 200;
|
||||||
private const int MaxPages = 5;
|
private const int MaxPages = 5;
|
||||||
private const int MaxDrivableObjectKind = 11;
|
private const int FirstNonRoadObjectKind = 12;
|
||||||
|
private const int LastNonRoadObjectKind = 19;
|
||||||
|
|
||||||
public virtual async Task<IReadOnlyList<RoadSegment>> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken)
|
public virtual async Task<IReadOnlyList<RoadSegment>> GetRoadSegmentsAsync(GeoPoint center, double radiusMeters, CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
|
|
@ -61,7 +62,10 @@ public partial class SwisstopoClient(HttpClient httpClient)
|
||||||
var isDrivable = !hasProperties
|
var isDrivable = !hasProperties
|
||||||
|| !properties.TryGetProperty("objektart", out var kind)
|
|| !properties.TryGetProperty("objektart", out var kind)
|
||||||
|| kind.ValueKind != JsonValueKind.Number
|
|| kind.ValueKind != JsonValueKind.Number
|
||||||
|| kind.GetInt32() <= MaxDrivableObjectKind;
|
|| 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 coordinates = geometry.GetProperty("coordinates");
|
||||||
var parts = geometry.GetProperty("type").GetString() switch
|
var parts = geometry.GetProperty("type").GetString() switch
|
||||||
|
|
@ -74,7 +78,8 @@ public partial class SwisstopoClient(HttpClient httpClient)
|
||||||
return parts.Select(part => new RoadSegment(
|
return parts.Select(part => new RoadSegment(
|
||||||
part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(),
|
part.EnumerateArray().Select(p => new GeoPoint(p[1].GetDouble(), p[0].GetDouble())).ToList(),
|
||||||
isMainRoad,
|
isMainRoad,
|
||||||
isDrivable));
|
isDrivable,
|
||||||
|
name));
|
||||||
}
|
}
|
||||||
|
|
||||||
public virtual async Task<GeoPoint?> FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken)
|
public virtual async Task<GeoPoint?> FindPlaceAsync(string name, GeoPoint near, CancellationToken cancellationToken)
|
||||||
|
|
|
||||||
|
|
@ -8,7 +8,7 @@ namespace Schaad.OpenData.Traffic.Storage;
|
||||||
public class TrafficCacheStorage(IOptions<TrafficOptions> options)
|
public class TrafficCacheStorage(IOptions<TrafficOptions> options)
|
||||||
{
|
{
|
||||||
private const string DayFormat = "yyyy-MM-dd";
|
private const string DayFormat = "yyyy-MM-dd";
|
||||||
private const string GeometryFileName = "geometry-v5.json";
|
private const string GeometryFileName = "geometry-v7.json";
|
||||||
|
|
||||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true };
|
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web) { WriteIndented = true };
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -38,7 +38,8 @@ public class TrafficRefresher(
|
||||||
public async Task BuildMissingGeometryAsync(CancellationToken cancellationToken)
|
public async Task BuildMissingGeometryAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
var snapshot = store.Current;
|
var snapshot = store.Current;
|
||||||
var missing = snapshot.Stations.Values.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList();
|
var stations = snapshot.Stations.Values.ToList();
|
||||||
|
var missing = stations.Where(s => !snapshot.Geometry.ContainsKey(s.Code)).ToList();
|
||||||
if (missing.Count == 0)
|
if (missing.Count == 0)
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
|
|
@ -49,7 +50,7 @@ public class TrafficRefresher(
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
built.Add(await geometryService.BuildAsync(station, cancellationToken));
|
built.Add(await geometryService.BuildAsync(station, stations, cancellationToken));
|
||||||
}
|
}
|
||||||
catch (HttpRequestException exception)
|
catch (HttpRequestException exception)
|
||||||
{
|
{
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue