From 1d71e440f9b51fbe50f187b1004c2568abec094c Mon Sep 17 00:00:00 2001 From: "vl.arkhangelskii" Date: Mon, 21 Sep 2026 13:48:00 +0300 Subject: [PATCH] fix(graph): tiles --- README.md | 4 +- .../2026-09-21_13-45-00_graph-mvt-tiles.md | 34 ++ ...6-09-21_13-50-00_cabinet-graph-examples.md | 9 + .../Controllers/PersonalDeliveryController.cs | 32 ++ .../DependencyInjection.cs | 1 + .../Graph/IRoadGraph.cs | 21 ++ .../Graph/RoadGraphTileService.cs | 136 ++++++++ .../Graph/RoadGraphZoomPolicy.cs | 36 ++ .../Tiles/GeographicBounds.cs | 26 ++ src/TileServer.Domain/Tiles/TileCoordinate.cs | 44 +++ .../DependencyInjection.cs | 1 + .../Graph/RoadGraphMvtEncoder.cs | 233 +++++++++++++ .../Graph/SqliteRoadGraphStore.cs | 80 ++++- tests/TileServer.UnitTests/RoadGraphTests.cs | 84 +++++ .../TileCoordinateTests.cs | 9 + web-demo/src/App.tsx | 321 +++++++----------- web-demo/src/access.ts | 10 +- web/src/features/graph/GraphPage.tsx | 67 +++- web/src/features/graph/graph.css | 20 ++ web/src/features/graph/graphExamples.ts | 142 ++++++++ web/src/features/guides/GuidesPage.tsx | 90 ++--- web/src/features/guides/guides.css | 18 + 22 files changed, 1153 insertions(+), 265 deletions(-) create mode 100644 context/2026-09-21_13-45-00_graph-mvt-tiles.md create mode 100644 context/2026-09-21_13-50-00_cabinet-graph-examples.md create mode 100644 src/TileServer.Application/Graph/RoadGraphTileService.cs create mode 100644 src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs create mode 100644 src/TileServer.Domain/Tiles/GeographicBounds.cs create mode 100644 src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs create mode 100644 web/src/features/graph/graphExamples.ts diff --git a/README.md b/README.md index 0efbad4..cc94ebf 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,8 @@ docker compose up -d --build | `GET` | `/u/{slug}/tiles/{source}/{z}/{x}/{y}.pbf?token=` | персональные тайлы | | `GET` | `/u/{slug}/styles/{name}?source=&token=` | персональный стиль | | `GET` | `/u/{slug}/graph/{source}?token=` | метаданные графа дорог | +| `GET` | `/u/{slug}/graph/{source}/{z}/{x}/{y}.pbf?token=` | векторные тайлы графа (слой `roads`) | +| `GET` | `/u/{slug}/graph/{source}/tiles.json?token=` | TileJSON графа | | `GET` | `/u/{slug}/graph/{source}/nodes?bbox=&token=` | узлы в bbox (пагинация `after`) | | `GET` | `/u/{slug}/graph/{source}/edges?bbox=&token=` | рёбра в bbox | | `GET` | `/api/v1/sources` | extract’ы и статус воркера | @@ -59,7 +61,7 @@ docker compose up -d --build | `POST` | `/api/v1/sync` | прогнать все extract’ы сейчас | | `POST` | `/api/v1/sync/{id}` | прогнать один extract | -Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`. +Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (на мелком зуме только крупные highway). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`. ## Несколько регионов diff --git a/context/2026-09-21_13-45-00_graph-mvt-tiles.md b/context/2026-09-21_13-45-00_graph-mvt-tiles.md new file mode 100644 index 0000000..d25e057 --- /dev/null +++ b/context/2026-09-21_13-45-00_graph-mvt-tiles.md @@ -0,0 +1,34 @@ +# Graph MVT tiles + web-demo overlay + +Date: 2026-09-21 + +## What + +Road graph is now served as XYZ vector tiles (MVT, layer `roads`) and wired into `web-demo` as a MapLibre vector source instead of a GeoJSON bbox fetch. + +## API + +- `GET /u/{slug}/graph/{source}/{z}/{x}/{y}.pbf?token=` +- `GET /u/{slug}/graph/{source}/tiles.json?token=` +- Metadata `links.tiles` / `links.tilejson` + +Encoding is on-the-fly from SQLite (`QueryEdgesInBoundsAsync`): tile Web Mercator bbox + 8% buffer, no 2° JSON cap. Cache key includes `builtAt`. Empty tiles are valid empty PBF (200). Zoom < 6 or > 18 → 204. + +Highway filter by zoom so a z6 tile does not pull the whole graph: + +- z ≤ 8: motorway/trunk (+ links) +- z ≤ 10: + primary +- z ≤ 12: + secondary/tertiary +- z 13+: all classes, cap 8000 features (longest first) + +Layer fields: `highway`, `name`, `oneway`, `length_m`. Geometry is vertex-to-vertex LineString. + +JSON bbox endpoints stay for point queries. + +## web-demo + +«Показать граф» adds `type: "vector"` sources for each selected extract with `graphReady`, `source-layer: roads`, orange overlay, minzoom 6 / maxzoom 14. Re-attaches after `setStyle`. + +## Deploy + +API must be redeployed for production `tile-server.ru`. Graph sqlite still has to exist (`graphs/{id}.sqlite` after sync with `BuildRoadGraph`). diff --git a/context/2026-09-21_13-50-00_cabinet-graph-examples.md b/context/2026-09-21_13-50-00_cabinet-graph-examples.md new file mode 100644 index 0000000..a66df6b --- /dev/null +++ b/context/2026-09-21_13-50-00_cabinet-graph-examples.md @@ -0,0 +1,9 @@ +# Cabinet graph docs and examples + +Date: 2026-09-21 + +## What + +Guides (`/guides`) step 5 is a real attach-graph instruction: load/idle, `source-layer: roads`, zooms, JSON bbox vs MVT, 404 if sqlite missing. Copy blocks include MapLibre overlay, HTML+React with graph, curl of a z14 tile at extract center, JSON pagination. + +Graph page (`/graph`) has a «Примеры» section with the same snippets filled from the selected extract, bbox and token (`web/src/features/graph/graphExamples.ts`). diff --git a/src/TileServer.Api/Controllers/PersonalDeliveryController.cs b/src/TileServer.Api/Controllers/PersonalDeliveryController.cs index 86d43cd..4936696 100644 --- a/src/TileServer.Api/Controllers/PersonalDeliveryController.cs +++ b/src/TileServer.Api/Controllers/PersonalDeliveryController.cs @@ -24,6 +24,7 @@ public sealed class PersonalDeliveryController( ITileQueryService tiles, IUserStyleService styles, IRoadGraphQueryService graphs, + IRoadGraphTileService graphTiles, IExtractCatalog extracts, IUsageRecorder usage, IOptions options) : ControllerBase @@ -114,6 +115,8 @@ public sealed class PersonalDeliveryController( builtAt = meta.BuiltAt, links = new { + tiles = $"{root}/u/{access.User.Slug}/graph/{source}/{{z}}/{{x}}/{{y}}.pbf?token={escaped}", + tilejson = $"{root}/u/{access.User.Slug}/graph/{source}/tiles.json?token={escaped}", nodes = $"{root}/u/{access.User.Slug}/graph/{source}/nodes?bbox={{minLon}},{{minLat}},{{maxLon}},{{maxLat}}&token={escaped}", edges = $"{root}/u/{access.User.Slug}/graph/{source}/edges?bbox={{minLon}},{{minLat}},{{maxLon}},{{maxLat}}&token={escaped}" } @@ -122,6 +125,35 @@ public sealed class PersonalDeliveryController( return Ok(payload); } + [HttpGet("graph/{source}/{z:int}/{x:int}/{y:int}.pbf")] + public async Task GetGraphTile(string slug, string source, int z, int x, int y, CancellationToken ct) + { + var access = await ResolveAsync(slug, ct).ConfigureAwait(false); + var result = await graphTiles.GetTileAsync(source, new TileCoordinate(z, x, y), ct).ConfigureAwait(false); + if (result is null) + { + Response.Headers.CacheControl = "no-store"; + usage.RecordGraph(access.User.Id, access.Token.Id, 0); + return NoContent(); + } + + var payload = result.Tile.Uncompressed(); + usage.RecordGraph(access.User.Id, access.Token.Id, payload.Length); + Response.Headers.CacheControl = "private, max-age=3600"; + return File(payload, "application/vnd.mapbox-vector-tile"); + } + + [HttpGet("graph/{source}/tiles.json")] + [Produces("application/json")] + public async Task GetGraphTileJson(string slug, string source, CancellationToken ct) + { + var access = await ResolveAsync(slug, ct).ConfigureAwait(false); + var token = AccessToken.Read(Request) ?? string.Empty; + var tilesUrl = + $"{PublicUrl.GetBase(Request, options)}/u/{access.User.Slug}/graph/{source}/{{z}}/{{x}}/{{y}}.pbf?token={Uri.EscapeDataString(token)}"; + return Ok(graphTiles.GetTileJson(source, tilesUrl)); + } + [HttpGet("graph/{source}/nodes")] [Produces("application/json")] public async Task GetGraphNodes( diff --git a/src/TileServer.Application/DependencyInjection.cs b/src/TileServer.Application/DependencyInjection.cs index d4dcbba..84af9b3 100644 --- a/src/TileServer.Application/DependencyInjection.cs +++ b/src/TileServer.Application/DependencyInjection.cs @@ -16,6 +16,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(sp => sp.GetRequiredService()); diff --git a/src/TileServer.Application/Graph/IRoadGraph.cs b/src/TileServer.Application/Graph/IRoadGraph.cs index 218f3d5..d14fc8d 100644 --- a/src/TileServer.Application/Graph/IRoadGraph.cs +++ b/src/TileServer.Application/Graph/IRoadGraph.cs @@ -1,5 +1,7 @@ +using TileServer.Application.Tiles; using TileServer.Domain.Extracts; using TileServer.Domain.Graph; +using TileServer.Domain.Tiles; namespace TileServer.Application.Graph; @@ -33,6 +35,25 @@ public interface IRoadGraphStore long afterId, int limit, CancellationToken ct); + + Task> QueryEdgesInBoundsAsync( + string extractId, + RoadGraphBounds bounds, + IReadOnlyList? highways, + int limit, + CancellationToken ct); +} + +public interface IRoadGraphMvtEncoder +{ + TileData Encode(IReadOnlyList edges, TileCoordinate tile); +} + +public interface IRoadGraphTileService +{ + Task GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct); + + TileJsonResponse GetTileJson(string extractId, string tilesUrl); } public interface IRoadGraphQueryService diff --git a/src/TileServer.Application/Graph/RoadGraphTileService.cs b/src/TileServer.Application/Graph/RoadGraphTileService.cs new file mode 100644 index 0000000..4418bb9 --- /dev/null +++ b/src/TileServer.Application/Graph/RoadGraphTileService.cs @@ -0,0 +1,136 @@ +using Microsoft.Extensions.Caching.Memory; +using Microsoft.Extensions.Logging; +using TileServer.Application.Extracts; +using TileServer.Application.Tiles; +using TileServer.Domain.Exceptions; +using TileServer.Domain.Graph; +using TileServer.Domain.Tiles; + +namespace TileServer.Application.Graph; + +public sealed class RoadGraphTileService( + IRoadGraphStore store, + IRoadGraphMvtEncoder encoder, + IExtractCatalog extracts, + IMemoryCache cache, + ILogger logger) : IRoadGraphTileService +{ + private const string Attribution = "© OpenStreetMap contributors"; + + public async Task GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct) + { + if (!tile.IsValid) + { + throw new DomainValidationException($"Invalid XYZ tile {tile.Z}/{tile.X}/{tile.Y}."); + } + + if (tile.Z < RoadGraphZoomPolicy.MinZoom || tile.Z > RoadGraphZoomPolicy.EncodeMaxZoom) + { + return null; + } + + var meta = store.GetMetadata(extractId); + if (meta is null) + { + throw new ResourceNotFoundException("RoadGraph", extractId); + } + + var cacheKey = $"graph:{extractId}/{tile.Z}/{tile.X}/{tile.Y}:{meta.BuiltAt.UtcTicks}"; + if (cache.TryGetValue(cacheKey, out TileData? cached) && cached is not null) + { + return new TileQueryResult(cached, extractId, meta.BuiltAt); + } + + var geo = tile.WebMercatorBounds(RoadGraphZoomPolicy.BufferFraction); + if (meta.Bounds is { } graphBounds) + { + var stored = new GeographicBounds( + graphBounds.MinLon, + graphBounds.MinLat, + graphBounds.MaxLon, + graphBounds.MaxLat); + if (!geo.Overlaps(stored)) + { + var miss = encoder.Encode([], tile); + SetCache(cacheKey, miss); + return new TileQueryResult(miss, extractId, meta.BuiltAt); + } + } + + var bounds = new RoadGraphBounds(geo.MinLon, geo.MinLat, geo.MaxLon, geo.MaxLat); + var highways = RoadGraphZoomPolicy.HighwaysForZoom(tile.Z); + IReadOnlyList edges; + try + { + edges = await store + .QueryEdgesInBoundsAsync(extractId, bounds, highways, RoadGraphZoomPolicy.MaxFeaturesPerTile, ct) + .ConfigureAwait(false); + } + catch (Exception ex) + { + logger.LogWarning(ex, "Failed to query graph edges for {ExtractId} tile {Tile}", extractId, $"{tile.Z}/{tile.X}/{tile.Y}"); + throw; + } + + var encoded = encoder.Encode(edges, tile); + SetCache(cacheKey, encoded); + return new TileQueryResult(encoded, extractId, meta.BuiltAt); + } + + public TileJsonResponse GetTileJson(string extractId, string tilesUrl) + { + var extract = extracts.GetRequired(extractId); + var meta = store.GetMetadata(extractId); + if (meta is null) + { + throw new ResourceNotFoundException("RoadGraph", extractId); + } + + var bounds = meta.Bounds is { } b + ? new[] { b.MinLon, b.MinLat, b.MaxLon, b.MaxLat } + : new[] { -180.0, -85.0511, 180.0, 85.0511 }; + var center = new[] + { + extract.CenterLon, + extract.CenterLat, + 10 + }; + + var fields = new Dictionary(StringComparer.Ordinal) + { + ["highway"] = "String", + ["name"] = "String", + ["oneway"] = "Boolean", + ["length_m"] = "Number" + }; + + return new TileJsonResponse( + Tilejson: "3.0.0", + Name: $"{extract.Name} (road graph)", + Tiles: [tilesUrl], + Bounds: bounds, + Center: center, + Minzoom: RoadGraphZoomPolicy.MinZoom, + Maxzoom: RoadGraphZoomPolicy.MaxZoom, + Format: "pbf", + Attribution: Attribution, + VectorLayers: + [ + new VectorLayerJson( + "roads", + "OSM highway segments as vertex-to-vertex edges", + RoadGraphZoomPolicy.MinZoom, + RoadGraphZoomPolicy.MaxZoom, + fields) + ]); + } + + private void SetCache(string key, TileData tile) + { + cache.Set(key, tile, new MemoryCacheEntryOptions + { + Size = 1, + SlidingExpiration = TimeSpan.FromMinutes(15) + }); + } +} diff --git a/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs b/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs new file mode 100644 index 0000000..d4f6123 --- /dev/null +++ b/src/TileServer.Application/Graph/RoadGraphZoomPolicy.cs @@ -0,0 +1,36 @@ +namespace TileServer.Application.Graph; + +public static class RoadGraphZoomPolicy +{ + public const int MinZoom = 6; + public const int MaxZoom = 14; + public const int EncodeMaxZoom = 18; + public const int MaxFeaturesPerTile = 8_000; + public const double BufferFraction = 0.08; + + private static readonly string[] Trunk = + ["motorway", "trunk", "motorway_link", "trunk_link"]; + + private static readonly string[] Primary = + ["motorway", "trunk", "motorway_link", "trunk_link", "primary", "primary_link"]; + + private static readonly string[] Secondary = + [ + "motorway", "trunk", "motorway_link", "trunk_link", + "primary", "primary_link", "secondary", "secondary_link", + "tertiary", "tertiary_link" + ]; + + /// + /// Low zooms keep only major highways so a 2°+ tile does not pull the whole graph. + /// Null means no filter (all classes). + /// + public static IReadOnlyList? HighwaysForZoom(int z) + => z switch + { + <= 8 => Trunk, + <= 10 => Primary, + <= 12 => Secondary, + _ => null + }; +} diff --git a/src/TileServer.Domain/Tiles/GeographicBounds.cs b/src/TileServer.Domain/Tiles/GeographicBounds.cs new file mode 100644 index 0000000..7bef006 --- /dev/null +++ b/src/TileServer.Domain/Tiles/GeographicBounds.cs @@ -0,0 +1,26 @@ +namespace TileServer.Domain.Tiles; + +public readonly record struct GeographicBounds(double MinLon, double MinLat, double MaxLon, double MaxLat) +{ + public bool Overlaps(GeographicBounds other) + => MinLon <= other.MaxLon + && MaxLon >= other.MinLon + && MinLat <= other.MaxLat + && MaxLat >= other.MinLat; + + public GeographicBounds Buffer(double fraction) + { + if (fraction <= 0) + { + return this; + } + + var dLon = (MaxLon - MinLon) * fraction; + var dLat = (MaxLat - MinLat) * fraction; + return new GeographicBounds( + Math.Max(-180, MinLon - dLon), + Math.Max(-85.05112878, MinLat - dLat), + Math.Min(180, MaxLon + dLon), + Math.Min(85.05112878, MaxLat + dLat)); + } +} diff --git a/src/TileServer.Domain/Tiles/TileCoordinate.cs b/src/TileServer.Domain/Tiles/TileCoordinate.cs index 1b5b69d..cb34b71 100644 --- a/src/TileServer.Domain/Tiles/TileCoordinate.cs +++ b/src/TileServer.Domain/Tiles/TileCoordinate.cs @@ -2,6 +2,9 @@ namespace TileServer.Domain.Tiles; public readonly record struct TileCoordinate(int Z, int X, int Y) { + public const int DefaultExtent = 4096; + private const double MaxMercatorLat = 85.05112878; + public bool IsValid { get @@ -16,6 +19,47 @@ public readonly record struct TileCoordinate(int Z, int X, int Y) } } + public static TileCoordinate FromLonLat(double lon, double lat, int z) + { + var n = 1 << z; + var x = (int)Math.Floor((lon + 180.0) / 360.0 * n); + var clampedLat = Math.Clamp(lat, -MaxMercatorLat, MaxMercatorLat); + var latRad = clampedLat * Math.PI / 180.0; + var y = (int)Math.Floor( + (1.0 - Math.Log(Math.Tan(latRad) + 1.0 / Math.Cos(latRad)) / Math.PI) / 2.0 * n); + x = Math.Clamp(x, 0, n - 1); + y = Math.Clamp(y, 0, n - 1); + return new TileCoordinate(z, x, y); + } + + public GeographicBounds WebMercatorBounds(double bufferFraction = 0) + { + var n = (double)(1 << Z); + var minLon = X / n * 360.0 - 180.0; + var maxLon = (X + 1) / n * 360.0 - 180.0; + var maxLat = MercatorNormToLat(Y / n); + var minLat = MercatorNormToLat((Y + 1) / n); + return new GeographicBounds(minLon, minLat, maxLon, maxLat).Buffer(bufferFraction); + } + + public (int X, int Y) ToTilePixels(double lon, double lat, int extent = DefaultExtent) + { + var n = (double)(1 << Z); + var clampedLat = Math.Clamp(lat, -MaxMercatorLat, MaxMercatorLat); + var latRad = clampedLat * Math.PI / 180.0; + var worldX = (lon + 180.0) / 360.0 * n; + var worldY = (1.0 - Math.Log(Math.Tan(latRad) + 1.0 / Math.Cos(latRad)) / Math.PI) / 2.0 * n; + var px = (int)Math.Round((worldX - X) * extent, MidpointRounding.AwayFromZero); + var py = (int)Math.Round((worldY - Y) * extent, MidpointRounding.AwayFromZero); + return (px, py); + } + + private static double MercatorNormToLat(double yNorm) + { + var n = Math.PI * (1.0 - 2.0 * yNorm); + return Math.Atan(Math.Sinh(n)) * 180.0 / Math.PI; + } + /// /// MBTiles stores TMS (origin south-west). MapLibre/XYZ origin is north-west. /// diff --git a/src/TileServer.Infrastructure/DependencyInjection.cs b/src/TileServer.Infrastructure/DependencyInjection.cs index c33270f..c0f7ec9 100644 --- a/src/TileServer.Infrastructure/DependencyInjection.cs +++ b/src/TileServer.Infrastructure/DependencyInjection.cs @@ -78,6 +78,7 @@ public static class DependencyInjection services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs b/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs new file mode 100644 index 0000000..115ad27 --- /dev/null +++ b/src/TileServer.Infrastructure/Graph/RoadGraphMvtEncoder.cs @@ -0,0 +1,233 @@ +using TileServer.Application.Graph; +using TileServer.Domain.Graph; +using TileServer.Domain.Tiles; +using TileServer.Infrastructure.Tiles.Mvt; + +namespace TileServer.Infrastructure.Graph; + +public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder +{ + public const int Extent = TileCoordinate.DefaultExtent; + public const int Buffer = 64; + public const string LayerName = "roads"; + + public TileData Encode(IReadOnlyList edges, TileCoordinate tile) + { + var layer = new MvtLayer + { + Version = 2, + Name = LayerName, + Extent = Extent + }; + var keys = new Dictionary(StringComparer.Ordinal); + var valueIndex = new Dictionary(StringComparer.Ordinal); + + foreach (var edge in edges) + { + var from = tile.ToTilePixels(edge.FromLon, edge.FromLat, Extent); + var to = tile.ToTilePixels(edge.ToLon, edge.ToLat, Extent); + if (!ClipSegment(from, to, out var a, out var b)) + { + continue; + } + + if (a.X == b.X && a.Y == b.Y) + { + continue; + } + + var tags = new List(8); + AddString(layer, keys, valueIndex, tags, "highway", edge.Highway); + if (!string.IsNullOrWhiteSpace(edge.Name)) + { + AddString(layer, keys, valueIndex, tags, "name", edge.Name); + } + + AddBool(layer, keys, valueIndex, tags, "oneway", edge.Oneway); + AddDouble(layer, keys, valueIndex, tags, "length_m", edge.LengthM); + + layer.Features.Add(new MvtFeature + { + Id = (ulong)Math.Max(0, edge.Id), + Type = MvtCodec.LineString, + Tags = tags, + Geometry = MvtCodec.EncodeGeometry([[a, b]], close: false) + }); + } + + var mvt = new MvtTile { Layers = { layer } }; + return MvtCodec.EncodeGzip(mvt); + } + + internal static bool ClipSegment( + (int X, int Y) from, + (int X, int Y) to, + out (int X, int Y) a, + out (int X, int Y) b) + { + var x0 = (double)from.X; + var y0 = (double)from.Y; + var x1 = (double)to.X; + var y1 = (double)to.Y; + var min = -Buffer; + var max = Extent + Buffer; + if (!CohenSutherland(ref x0, ref y0, ref x1, ref y1, min, max)) + { + a = default; + b = default; + return false; + } + + a = ((int)Math.Round(x0, MidpointRounding.AwayFromZero), (int)Math.Round(y0, MidpointRounding.AwayFromZero)); + b = ((int)Math.Round(x1, MidpointRounding.AwayFromZero), (int)Math.Round(y1, MidpointRounding.AwayFromZero)); + return true; + } + + private static void AddString( + MvtLayer layer, + Dictionary keys, + Dictionary values, + List tags, + string key, + string value) + { + tags.Add(KeyIndex(layer, keys, key)); + tags.Add(Intern(layer, values, "s:" + value, new MvtValue { StringValue = value })); + } + + private static void AddBool( + MvtLayer layer, + Dictionary keys, + Dictionary values, + List tags, + string key, + bool value) + { + tags.Add(KeyIndex(layer, keys, key)); + tags.Add(Intern(layer, values, value ? "b:1" : "b:0", new MvtValue { BoolValue = value })); + } + + private static void AddDouble( + MvtLayer layer, + Dictionary keys, + Dictionary values, + List tags, + string key, + double value) + { + tags.Add(KeyIndex(layer, keys, key)); + var intern = "d:" + value.ToString("G9", System.Globalization.CultureInfo.InvariantCulture); + tags.Add(Intern(layer, values, intern, new MvtValue { DoubleValue = value })); + } + + private static uint KeyIndex(MvtLayer layer, Dictionary keys, string key) + { + if (keys.TryGetValue(key, out var index)) + { + return index; + } + + index = (uint)layer.Keys.Count; + layer.Keys.Add(key); + keys[key] = index; + return index; + } + + private static uint Intern(MvtLayer layer, Dictionary values, string internKey, MvtValue value) + { + if (values.TryGetValue(internKey, out var index)) + { + return index; + } + + index = (uint)layer.Values.Count; + layer.Values.Add(value); + values[internKey] = index; + return index; + } + + private static bool CohenSutherland( + ref double x0, + ref double y0, + ref double x1, + ref double y1, + double min, + double max) + { + var out0 = OutCode(x0, y0, min, max); + var out1 = OutCode(x1, y1, min, max); + while (true) + { + if ((out0 | out1) == 0) + { + return true; + } + + if ((out0 & out1) != 0) + { + return false; + } + + var code = out0 != 0 ? out0 : out1; + double x; + double y; + if ((code & 8) != 0) + { + x = x0 + (x1 - x0) * (max - y0) / (y1 - y0); + y = max; + } + else if ((code & 4) != 0) + { + x = x0 + (x1 - x0) * (min - y0) / (y1 - y0); + y = min; + } + else if ((code & 2) != 0) + { + y = y0 + (y1 - y0) * (max - x0) / (x1 - x0); + x = max; + } + else + { + y = y0 + (y1 - y0) * (min - x0) / (x1 - x0); + x = min; + } + + if (code == out0) + { + x0 = x; + y0 = y; + out0 = OutCode(x0, y0, min, max); + } + else + { + x1 = x; + y1 = y; + out1 = OutCode(x1, y1, min, max); + } + } + } + + private static int OutCode(double x, double y, double min, double max) + { + var code = 0; + if (x < min) + { + code |= 1; + } + else if (x > max) + { + code |= 2; + } + + if (y < min) + { + code |= 4; + } + else if (y > max) + { + code |= 8; + } + + return code; + } +} diff --git a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs index b8d5e23..ae1a09a 100644 --- a/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs +++ b/src/TileServer.Infrastructure/Graph/SqliteRoadGraphStore.cs @@ -161,23 +161,79 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger(items, next); } + public async Task> QueryEdgesInBoundsAsync( + string extractId, + RoadGraphBounds bounds, + IReadOnlyList? highways, + int limit, + CancellationToken ct) + { + await using var connection = Open(paths.RoadGraph(extractId)); + await using var command = connection.CreateCommand(); + var highwayFilter = ""; + if (highways is { Count: > 0 }) + { + var names = new string[highways.Count]; + for (var i = 0; i < highways.Count; i++) + { + var param = $"$h{i}"; + names[i] = param; + command.Parameters.AddWithValue(param, highways[i]); + } + + highwayFilter = $" AND e.highway IN ({string.Join(", ", names)})"; + } + + command.CommandText = + $""" + SELECT e.id, e.from_id, e.to_id, e.highway, e.name, e.oneway, e.length_m, + a.lon, a.lat, b.lon, b.lat + FROM edges e + INNER JOIN nodes a ON a.id = e.from_id + INNER JOIN nodes b ON b.id = e.to_id + WHERE ( + (a.lon BETWEEN $minLon AND $maxLon AND a.lat BETWEEN $minLat AND $maxLat) + OR (b.lon BETWEEN $minLon AND $maxLon AND b.lat BETWEEN $minLat AND $maxLat) + ){highwayFilter} + ORDER BY e.length_m DESC + LIMIT $limit; + """; + command.Parameters.AddWithValue("$minLon", bounds.MinLon); + command.Parameters.AddWithValue("$maxLon", bounds.MaxLon); + command.Parameters.AddWithValue("$minLat", bounds.MinLat); + command.Parameters.AddWithValue("$maxLat", bounds.MaxLat); + command.Parameters.AddWithValue("$limit", Math.Max(1, limit)); + + var items = new List(Math.Min(limit, 1024)); + await using var reader = await command.ExecuteReaderAsync(ct).ConfigureAwait(false); + while (await reader.ReadAsync(ct).ConfigureAwait(false)) + { + items.Add(ReadEdge(reader, reader.GetInt64(0))); + } + + return items; + } + + private static RoadGraphEdge ReadEdge(SqliteDataReader reader, long id) + => new( + id, + reader.GetInt64(1), + reader.GetInt64(2), + reader.GetString(3), + reader.IsDBNull(4) ? null : reader.GetString(4), + reader.GetInt64(5) != 0, + reader.GetDouble(6), + reader.GetDouble(7), + reader.GetDouble(8), + reader.GetDouble(9), + reader.GetDouble(10)); + private static SqliteConnection Open(string path) { var connection = new SqliteConnection(new SqliteConnectionStringBuilder diff --git a/tests/TileServer.UnitTests/RoadGraphTests.cs b/tests/TileServer.UnitTests/RoadGraphTests.cs index 4dd1aaf..3084ca2 100644 --- a/tests/TileServer.UnitTests/RoadGraphTests.cs +++ b/tests/TileServer.UnitTests/RoadGraphTests.cs @@ -1,7 +1,9 @@ using TileServer.Application.Graph; using TileServer.Domain.Exceptions; using TileServer.Domain.Graph; +using TileServer.Domain.Tiles; using TileServer.Infrastructure.Graph; +using TileServer.Infrastructure.Tiles.Mvt; namespace TileServer.UnitTests; @@ -26,4 +28,86 @@ public sealed class RoadGraphTests { RoadGraphQueryService.ValidateBounds(new RoadGraphBounds(37.5, 55.7, 37.7, 55.8)); } + + [Theory] + [InlineData(6, "motorway")] + [InlineData(8, "trunk")] + [InlineData(10, "primary")] + [InlineData(12, "tertiary")] + public void HighwaysForZoom_IncludesMajorClasses(int z, string highway) + { + var list = RoadGraphZoomPolicy.HighwaysForZoom(z); + Assert.NotNull(list); + Assert.Contains(highway, list); + } + + [Fact] + public void HighwaysForZoom_AllClassesAtStreetLevel() + => Assert.Null(RoadGraphZoomPolicy.HighwaysForZoom(13)); +} + +public sealed class RoadGraphMvtTests +{ + [Fact] + public void WorldTile_CoversWebMercator() + { + var bounds = new TileCoordinate(0, 0, 0).WebMercatorBounds(); + Assert.InRange(bounds.MinLon, -180.01, -179.99); + Assert.InRange(bounds.MaxLon, 179.99, 180.01); + Assert.True(bounds.MaxLat > 85); + Assert.True(bounds.MinLat < -85); + } + + [Fact] + public void FromLonLat_MoscowTileContainsPoint() + { + const double lon = 37.6173; + const double lat = 55.7558; + var tile = TileCoordinate.FromLonLat(lon, lat, 14); + var bounds = tile.WebMercatorBounds(); + Assert.InRange(lon, bounds.MinLon, bounds.MaxLon); + Assert.InRange(lat, bounds.MinLat, bounds.MaxLat); + } + + [Fact] + public void Encode_SingleEdge_ProducesRoadsLayer() + { + var tile = TileCoordinate.FromLonLat(37.6173, 55.7558, 14); + var edge = new RoadGraphEdge( + 1, 10, 11, "primary", "Tverskaya", false, 120, + 37.6173, 55.7558, 37.6185, 55.7562); + var data = new RoadGraphMvtEncoder().Encode([edge], tile); + var decoded = MvtCodec.Decode(data); + var layer = Assert.Single(decoded.Layers); + Assert.Equal(RoadGraphMvtEncoder.LayerName, layer.Name); + Assert.Equal(RoadGraphMvtEncoder.Extent, (int)layer.Extent); + var feature = Assert.Single(layer.Features); + Assert.Equal(MvtCodec.LineString, feature.Type); + Assert.Contains("highway", layer.Keys); + Assert.True(feature.Geometry.Count >= 6); + } + + [Fact] + public void Encode_Empty_KeepsRoadsLayer() + { + var tile = new TileCoordinate(10, 619, 320); + var data = new RoadGraphMvtEncoder().Encode([], tile); + var decoded = MvtCodec.Decode(data); + var layer = Assert.Single(decoded.Layers); + Assert.Equal(RoadGraphMvtEncoder.LayerName, layer.Name); + Assert.Empty(layer.Features); + } + + [Fact] + public void ClipSegment_RejectsFullyOutside() + { + Assert.False(RoadGraphMvtEncoder.ClipSegment((-2000, 100), (-1800, 200), out _, out _)); + } + + [Fact] + public void ClipSegment_KeepsCrossingLine() + { + Assert.True(RoadGraphMvtEncoder.ClipSegment((-100, 100), (5000, 2000), out var a, out var b)); + Assert.NotEqual(a, b); + } } diff --git a/tests/TileServer.UnitTests/TileCoordinateTests.cs b/tests/TileServer.UnitTests/TileCoordinateTests.cs index 42a6c9e..af0d3c0 100644 --- a/tests/TileServer.UnitTests/TileCoordinateTests.cs +++ b/tests/TileServer.UnitTests/TileCoordinateTests.cs @@ -34,6 +34,15 @@ public sealed class TileCoordinateTests [InlineData(-1, 0, 0, false)] public void IsValid_RespectsZoomBounds(int z, int x, int y, bool expected) => Assert.Equal(expected, new TileCoordinate(z, x, y).IsValid); + + [Fact] + public void FromLonLat_PixelsStayInsideExtent() + { + var tile = TileCoordinate.FromLonLat(37.6173, 55.7558, 12); + var (px, py) = tile.ToTilePixels(37.6173, 55.7558); + Assert.InRange(px, 0, TileCoordinate.DefaultExtent); + Assert.InRange(py, 0, TileCoordinate.DefaultExtent); + } } public sealed class ResourceNameTests diff --git a/web-demo/src/App.tsx b/web-demo/src/App.tsx index d0f619e..f22bc85 100644 --- a/web-demo/src/App.tsx +++ b/web-demo/src/App.tsx @@ -3,9 +3,8 @@ import maplibregl, { type Map as MapLibreMap, type StyleSpecification } from "ma import "maplibre-gl/dist/maplibre-gl.css"; import { API_ORIGIN, - graphEdgesUrl, graphMetaUrl, - graphNodesUrl, + graphTilesUrl, isPersonal, persistAccess, readAccess, @@ -17,10 +16,7 @@ import { } from "./access"; import { fetchJson, - type GraphEdge, type GraphMeta, - type GraphNode, - type GraphPage, type SourceItem, type StyleItem, type SyncStatus @@ -35,10 +31,9 @@ const STATUS_LABELS: Record = { Failed: "ошибка" }; -const GRAPH_SOURCE = "demo-road-graph"; -const GRAPH_LAYER = "demo-road-graph-line"; -const GRAPH_CASING = "demo-road-graph-casing"; -const MAX_BBOX_SPAN = 2; +const GRAPH_PREFIX = "demo-road-graph"; +const GRAPH_MIN_ZOOM = 6; +const GRAPH_MAX_ZOOM = 14; function formatStatus(value?: string): string { return STATUS_LABELS[value ?? ""] ?? value ?? "—"; @@ -81,122 +76,84 @@ function cameraFromHash(): { zoom: number; lat: number; lon: number } | null { return { zoom, lat, lon }; } -/** Clamp map viewport to API max span (2°) around center. */ -function bboxFromMap(map: MapLibreMap): string { - const bounds = map.getBounds(); - const center = map.getCenter(); - let west = bounds.getWest(); - let east = bounds.getEast(); - let south = bounds.getSouth(); - let north = bounds.getNorth(); - if (east - west > MAX_BBOX_SPAN) { - const half = MAX_BBOX_SPAN / 2; - west = center.lng - half; - east = center.lng + half; - } - if (north - south > MAX_BBOX_SPAN) { - const half = MAX_BBOX_SPAN / 2; - south = center.lat - half; - north = center.lat + half; - } - return `${west.toFixed(5)},${south.toFixed(5)},${east.toFixed(5)},${north.toFixed(5)}`; +function graphSourceId(extractId: string): string { + return `${GRAPH_PREFIX}-${extractId}`; } -function edgesToGeoJson(nodes: GraphNode[], edges: GraphEdge[]): GeoJSON.FeatureCollection { - const byId = new Map(nodes.map((node) => [node.id, node])); - const features: GeoJSON.Feature[] = []; - for (const edge of edges) { - const from = hasCoords(edge.fromLon, edge.fromLat) - ? { lon: edge.fromLon as number, lat: edge.fromLat as number } - : byId.get(edge.fromId); - const to = hasCoords(edge.toLon, edge.toLat) - ? { lon: edge.toLon as number, lat: edge.toLat as number } - : byId.get(edge.toId); - if (!from || !to) { - continue; - } - features.push({ - type: "Feature", - properties: { - id: edge.id, - highway: edge.highway, - name: edge.name ?? "", - oneway: edge.oneway, - lengthM: edge.lengthM - }, - geometry: { - type: "LineString", - coordinates: [ - [from.lon, from.lat], - [to.lon, to.lat] - ] +function graphCasingId(extractId: string): string { + return `${GRAPH_PREFIX}-${extractId}-casing`; +} + +function graphLineId(extractId: string): string { + return `${GRAPH_PREFIX}-${extractId}-line`; +} + +function attachGraphTiles(map: MapLibreMap, access: Access, sources: SourceItem[]): string | null { + if (!map.isStyleLoaded()) { + return "Стиль карты ещё грузится — повтори через секунду."; + } + + clearGraphLayers(map); + const ready = sources.filter((item) => item.graphReady !== false); + if (ready.length === 0) { + return "У выбранных округов граф ещё не собран. Синхронизируй extract."; + } + + for (const item of ready) { + const sourceId = graphSourceId(item.id); + map.addSource(sourceId, { + type: "vector", + tiles: [graphTilesUrl(access, item.id)], + minzoom: GRAPH_MIN_ZOOM, + maxzoom: GRAPH_MAX_ZOOM + }); + map.addLayer({ + id: graphCasingId(item.id), + type: "line", + source: sourceId, + "source-layer": "roads", + paint: { + "line-color": "#1a1208", + "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 10, 3.2, 14, 6], + "line-opacity": 0.85 + } + }); + map.addLayer({ + id: graphLineId(item.id), + type: "line", + source: sourceId, + "source-layer": "roads", + paint: { + "line-color": "#ffb45a", + "line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6], + "line-opacity": 1 } }); } - return { type: "FeatureCollection", features }; -} -function hasCoords(lon?: number, lat?: number): boolean { - return Number.isFinite(lon) && Number.isFinite(lat); -} - -function ensureGraphLayers(map: MapLibreMap, data: GeoJSON.FeatureCollection): void { - const paint = () => { - if (map.loaded() === false || !map.isStyleLoaded()) { - map.once("idle", paint); - return; - } - - const existing = map.getSource(GRAPH_SOURCE) as maplibregl.GeoJSONSource | undefined; - if (existing) { - existing.setData(data); - } else { - map.addSource(GRAPH_SOURCE, { type: "geojson", data }); - map.addLayer({ - id: GRAPH_CASING, - type: "line", - source: GRAPH_SOURCE, - paint: { - "line-color": "#1a1208", - "line-width": 5.5, - "line-opacity": 0.85 - } - }); - map.addLayer({ - id: GRAPH_LAYER, - type: "line", - source: GRAPH_SOURCE, - paint: { - "line-color": "#ffb45a", - "line-width": 3.2, - "line-opacity": 1 - } - }); - } - - if (map.getLayer(GRAPH_CASING)) { - map.moveLayer(GRAPH_CASING); - } - if (map.getLayer(GRAPH_LAYER)) { - map.moveLayer(GRAPH_LAYER); - } - }; - - paint(); + return null; } function clearGraphLayers(map: MapLibreMap | null): void { if (!map) { return; } - if (map.getLayer(GRAPH_LAYER)) { - map.removeLayer(GRAPH_LAYER); + + const style = map.getStyle(); + if (!style) { + return; } - if (map.getLayer(GRAPH_CASING)) { - map.removeLayer(GRAPH_CASING); + + for (const layer of [...(style.layers ?? [])]) { + if (layer.id.startsWith(`${GRAPH_PREFIX}-`)) { + map.removeLayer(layer.id); + } } - if (map.getSource(GRAPH_SOURCE)) { - map.removeSource(GRAPH_SOURCE); + + for (const id of Object.keys(style.sources ?? {})) { + if (id.startsWith(`${GRAPH_PREFIX}-`)) { + map.removeSource(id); + } } } @@ -221,11 +178,7 @@ export function App() { const [graphLoading, setGraphLoading] = useState(false); const [graphError, setGraphError] = useState(""); const [graphMeta, setGraphMeta] = useState(null); - const [graphEdgeCount, setGraphEdgeCount] = useState(0); - const [graphNodeCount, setGraphNodeCount] = useState(0); - const [graphBbox, setGraphBbox] = useState(""); - const [graphSample, setGraphSample] = useState([]); - const [graphDrawn, setGraphDrawn] = useState(0); + const [graphEnabled, setGraphEnabled] = useState(false); const [access, setAccess] = useState(() => { const stored = readAccess(); persistAccess(stored); @@ -235,12 +188,16 @@ export function App() { const [tokenDraft, setTokenDraft] = useState(access.token); const accessRef = useRef(access); accessRef.current = access; + const graphEnabledRef = useRef(graphEnabled); + graphEnabledRef.current = graphEnabled; + const selectedSourcesRef = useRef([]); const personal = isPersonal(access); const selectedSources = sources.filter((item) => selectedSourceIds.includes(item.id)); + selectedSourcesRef.current = selectedSources; const source = selectedSources[0] ?? sources[0]; - const graphSource = - selectedSources.find((item) => item.graphReady !== false) ?? selectedSources[0] ?? sources[0]; + const graphSources = selectedSources.filter((item) => item.graphReady !== false); + const graphSource = graphSources[0] ?? selectedSources[0] ?? sources[0]; const updateHud = useCallback((map: MapLibreMap) => { const center = map.getCenter(); @@ -325,6 +282,12 @@ export function App() { map.resize(); updateHud(map); syncGotoFromMap(map); + if (graphEnabledRef.current) { + const err = attachGraphTiles(map, accessRef.current, selectedSourcesRef.current); + if (err) { + setGraphError(err); + } + } }); map.on("error", (event) => { const message = event.error?.message; @@ -334,14 +297,17 @@ export function App() { }); mapRef.current = map; } else { - clearGraphLayers(mapRef.current); mapRef.current.setStyle(style, { diff: false }); - setGraphMeta(null); - setGraphEdgeCount(0); - setGraphNodeCount(0); - setGraphSample([]); - setGraphDrawn(0); - setGraphBbox(""); + mapRef.current.once("idle", () => { + const current = mapRef.current; + if (!current || !graphEnabledRef.current) { + return; + } + const err = attachGraphTiles(current, accessRef.current, selectedSourcesRef.current); + if (err) { + setGraphError(err); + } + }); } styleKeyRef.current = styleKey; @@ -453,13 +419,10 @@ export function App() { }; const clearGraph = () => { + graphEnabledRef.current = false; + setGraphEnabled(false); clearGraphLayers(mapRef.current); setGraphMeta(null); - setGraphEdgeCount(0); - setGraphNodeCount(0); - setGraphSample([]); - setGraphDrawn(0); - setGraphBbox(""); setGraphError(""); }; @@ -469,48 +432,45 @@ export function App() { return; } const map = mapRef.current; - if (!map || !graphSource) { - setGraphError("Карта или источник ещё не готовы."); + if (!map) { + setGraphError("Карта ещё не готова."); return; } - if (graphSource.graphReady === false) { - setGraphError(`Граф «${graphSource.name}» ещё не собран. Синхронизируй extract.`); + if (graphSources.length === 0) { + setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract."); return; } - const bbox = bboxFromMap(map); setGraphLoading(true); setGraphError(""); try { - const [meta, nodesPage, edgesPage] = await Promise.all([ - fetchJson(graphMetaUrl(access, graphSource.id)), - fetchJson>(graphNodesUrl(access, graphSource.id, bbox, 0, 5000)), - fetchJson>(graphEdgesUrl(access, graphSource.id, bbox, 0, 5000)) - ]); - const nodes = nodesPage.items ?? []; - const edges = edgesPage.items ?? []; - const geo = edgesToGeoJson(nodes, edges); - ensureGraphLayers(map, geo); - setGraphMeta(meta); - setGraphNodeCount(nodes.length); - setGraphEdgeCount(edges.length); - setGraphDrawn(geo.features.length); - setGraphSample(edges.slice(0, 8)); - setGraphBbox(bbox); - setBanner(""); - if (edges.length === 0) { - setGraphError("В этом кадре API вернул 0 рёбер. Приблизь карту (зум 13+, Москва) или собери граф через sync."); - } else if (geo.features.length === 0) { - setGraphError( - "Рёбра есть, но без координат на карте. Задеплой API: edges должны отдавать fromLon/fromLat/toLon/toLat." - ); + const meta = await fetchJson(graphMetaUrl(access, graphSources[0].id)); + const waitStyle = () => + new Promise((resolve) => { + if (map.isStyleLoaded()) { + resolve(); + return; + } + map.once("idle", () => resolve()); + }); + await waitStyle(); + const err = attachGraphTiles(map, access, selectedSources); + if (err) { + setGraphError(err); + setGraphEnabled(false); + graphEnabledRef.current = false; + return; } + graphEnabledRef.current = true; + setGraphEnabled(true); + setGraphMeta(meta); + setBanner(""); } catch (err: unknown) { clearGraphLayers(map); + setGraphEnabled(false); + graphEnabledRef.current = false; setGraphMeta(null); - setGraphSample([]); - setGraphDrawn(0); - setGraphError(err instanceof Error ? err.message : "Не удалось загрузить граф"); + setGraphError(err instanceof Error ? err.message : "Не удалось подключить тайлы графа"); } finally { setGraphLoading(false); } @@ -657,20 +617,24 @@ export function App() { Граф дорог

- Берёт bbox текущего viewport (≤ 2°) и первый выбранный округ - {graphSource ? ` («${graphSource.name}»)` : ""}. Нажми «Проверить viewport» — рёбра - рисуются оранжевым поверх карты. На широком зуме сначала жми «Москва». + Векторные тайлы graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf + {graphSources.length > 0 + ? ` — ${graphSources.map((item) => `«${item.name}»`).join(", ")}` + : graphSource + ? ` («${graphSource.name}»)` + : ""} + . Слой roads, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}. Оранжевые линии поверх OSM.

-
@@ -688,18 +652,8 @@ export function App() {
-
В bbox
-
- {formatNumber(graphNodeCount)} узл. · {formatNumber(graphEdgeCount)} рёбер -
-
-
-
Нарисовано
-
{formatNumber(graphDrawn)} линий
-
-
-
bbox
-
{graphBbox}
+
Слои
+
{graphEnabled ? `${graphSources.length} vector source` : "выкл"}
Собран
@@ -707,17 +661,6 @@ export function App() {
) : null} - {graphSample.length > 0 ? ( -
    - {graphSample.map((edge) => ( -
  • - {edge.highway} - {edge.name || `${edge.fromId}→${edge.toId}`} - {Math.round(edge.lengthM)} м -
  • - ))} -
- ) : null} diff --git a/web-demo/src/access.ts b/web-demo/src/access.ts index 9ce5798..6f8eaa3 100644 --- a/web-demo/src/access.ts +++ b/web-demo/src/access.ts @@ -70,15 +70,9 @@ export function graphMetaUrl(access: Access, sourceId: string): string { ); } -export function graphNodesUrl(access: Access, sourceId: string, bbox: string, after = 0, limit = 5000): string { +export function graphTilesUrl(access: Access, sourceId: string): string { return serviceUrl( - `/u/${encodeURIComponent(access.slug)}/graph/${encodeURIComponent(sourceId)}/nodes?bbox=${encodeURIComponent(bbox)}&after=${after}&limit=${limit}&token=${encodeURIComponent(access.token)}` - ); -} - -export function graphEdgesUrl(access: Access, sourceId: string, bbox: string, after = 0, limit = 5000): string { - return serviceUrl( - `/u/${encodeURIComponent(access.slug)}/graph/${encodeURIComponent(sourceId)}/edges?bbox=${encodeURIComponent(bbox)}&after=${after}&limit=${limit}&token=${encodeURIComponent(access.token)}` + `/u/${encodeURIComponent(access.slug)}/graph/${encodeURIComponent(sourceId)}/{z}/{x}/{y}.pbf?token=${encodeURIComponent(access.token)}` ); } diff --git a/web/src/features/graph/GraphPage.tsx b/web/src/features/graph/GraphPage.tsx index ec8a85c..219441b 100644 --- a/web/src/features/graph/GraphPage.tsx +++ b/web/src/features/graph/GraphPage.tsx @@ -9,6 +9,7 @@ import { import { Button, Flash, PageHeader, Section } from "../../components/ui"; import { AppSelect, AppTextField } from "../../ui"; import { useAuth } from "../auth/AuthContext"; +import { buildGraphExamples } from "./graphExamples"; import "./graph.css"; type GraphMeta = { @@ -42,10 +43,10 @@ function formatNumber(value: number): string { return value.toLocaleString("ru-RU"); } -function CopyField({ label, value }: { label: string; value: string }) { +function CopyField({ label, value, code }: { label: string; value: string; code?: boolean }) { const [copied, setCopied] = useState(false); return ( -
+
{label}