OpenDataVisualizer/Schaad.OpenData.Vehicles/Source/MunicipalityBoundaryClient.cs
Claudio Schaad 688775e742 Add Thurgau vehicle stock map (#3)
Choropleth of the 80 Thurgau municipalities from the road vehicle stock dataset (djs-stv-17), with population from sk-stat-56 and outlines from swisstopo. Also fixes the broken ENV line in the Dockerfile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Claudio Schaad <c.schaad@pog.ch>
Co-committed-by: Claudio Schaad <c.schaad@pog.ch>
2026-11-06 21:43:23 +00:00

50 lines
2 KiB
C#

using System.Text.Json;
using Microsoft.Extensions.Options;
using Schaad.OpenData.Vehicles.Models;
namespace Schaad.OpenData.Vehicles.Source;
public class MunicipalityBoundaryClient(HttpClient httpClient, IOptions<VehicleOptions> options)
{
private const int Decimals = 5;
public virtual async Task<MunicipalityOutline?> FetchAsync(string municipalityId, CancellationToken cancellationToken)
{
var url = $"{options.Value.BoundaryUrl}/{Uri.EscapeDataString(municipalityId)}?geometryFormat=geojson&sr=4326";
using var response = await httpClient.GetAsync(url, cancellationToken);
if (!response.IsSuccessStatusCode)
{
return null;
}
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var document = await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
if (!document.RootElement.TryGetProperty("feature", out var feature)
|| !feature.TryGetProperty("geometry", out var geometry)
|| !geometry.TryGetProperty("type", out var typeElement)
|| !geometry.TryGetProperty("coordinates", out var coordinates))
{
return null;
}
double[][][][] polygons = typeElement.GetString() switch
{
"Polygon" => [ReadPolygon(coordinates)],
"MultiPolygon" => coordinates.EnumerateArray().Select(ReadPolygon).ToArray(),
_ => [],
};
return polygons.Length == 0 ? null : new MunicipalityOutline(municipalityId, polygons);
}
private static double[][][] ReadPolygon(JsonElement polygon) =>
polygon.EnumerateArray()
.Select(ring => ring.EnumerateArray()
.Select(point => new[]
{
Math.Round(point[0].GetDouble(), Decimals),
Math.Round(point[1].GetDouble(), Decimals),
})
.ToArray())
.ToArray();
}