fix(graph): tiles
This commit is contained in:
@@ -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`.
|
||||
|
||||
## Несколько регионов
|
||||
|
||||
|
||||
@@ -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`).
|
||||
@@ -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`).
|
||||
@@ -24,6 +24,7 @@ public sealed class PersonalDeliveryController(
|
||||
ITileQueryService tiles,
|
||||
IUserStyleService styles,
|
||||
IRoadGraphQueryService graphs,
|
||||
IRoadGraphTileService graphTiles,
|
||||
IExtractCatalog extracts,
|
||||
IUsageRecorder usage,
|
||||
IOptions<TileServerOptions> 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<IActionResult> 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<IActionResult> 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<IActionResult> GetGraphNodes(
|
||||
|
||||
@@ -16,6 +16,7 @@ public static class DependencyInjection
|
||||
services.AddSingleton<IStyleService, StyleService>();
|
||||
services.AddSingleton<IExtractService, ExtractService>();
|
||||
services.AddSingleton<IRoadGraphQueryService, RoadGraphQueryService>();
|
||||
services.AddSingleton<IRoadGraphTileService, RoadGraphTileService>();
|
||||
services.AddSingleton<IMapSyncService, MapSyncService>();
|
||||
services.AddSingleton<UsageAccumulator>();
|
||||
services.AddSingleton<IUsageRecorder>(sp => sp.GetRequiredService<UsageAccumulator>());
|
||||
|
||||
@@ -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<IReadOnlyList<RoadGraphEdge>> QueryEdgesInBoundsAsync(
|
||||
string extractId,
|
||||
RoadGraphBounds bounds,
|
||||
IReadOnlyList<string>? highways,
|
||||
int limit,
|
||||
CancellationToken ct);
|
||||
}
|
||||
|
||||
public interface IRoadGraphMvtEncoder
|
||||
{
|
||||
TileData Encode(IReadOnlyList<RoadGraphEdge> edges, TileCoordinate tile);
|
||||
}
|
||||
|
||||
public interface IRoadGraphTileService
|
||||
{
|
||||
Task<TileQueryResult?> GetTileAsync(string extractId, TileCoordinate tile, CancellationToken ct);
|
||||
|
||||
TileJsonResponse GetTileJson(string extractId, string tilesUrl);
|
||||
}
|
||||
|
||||
public interface IRoadGraphQueryService
|
||||
|
||||
@@ -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<RoadGraphTileService> logger) : IRoadGraphTileService
|
||||
{
|
||||
private const string Attribution = "© OpenStreetMap contributors";
|
||||
|
||||
public async Task<TileQueryResult?> 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<RoadGraphEdge> 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<string, string>(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)
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Low zooms keep only major highways so a 2°+ tile does not pull the whole graph.
|
||||
/// Null means no filter (all classes).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string>? HighwaysForZoom(int z)
|
||||
=> z switch
|
||||
{
|
||||
<= 8 => Trunk,
|
||||
<= 10 => Primary,
|
||||
<= 12 => Secondary,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MBTiles stores TMS (origin south-west). MapLibre/XYZ origin is north-west.
|
||||
/// </summary>
|
||||
|
||||
@@ -78,6 +78,7 @@ public static class DependencyInjection
|
||||
services.AddSingleton<ITileBuilder, PlanetilerTileBuilder>();
|
||||
services.AddSingleton<IRoadGraphStore, SqliteRoadGraphStore>();
|
||||
services.AddSingleton<IRoadGraphBuilder, OsmSharpRoadGraphBuilder>();
|
||||
services.AddSingleton<IRoadGraphMvtEncoder, RoadGraphMvtEncoder>();
|
||||
services.AddSingleton<IPlanetilerBootstrapper, PlanetilerJarBootstrapper>();
|
||||
services.AddSingleton<IPlanetilerSourceBootstrapper, PlanetilerSourceBootstrapper>();
|
||||
services.AddSingleton<IStyleCatalog, FileStyleCatalog>();
|
||||
|
||||
@@ -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<RoadGraphEdge> edges, TileCoordinate tile)
|
||||
{
|
||||
var layer = new MvtLayer
|
||||
{
|
||||
Version = 2,
|
||||
Name = LayerName,
|
||||
Extent = Extent
|
||||
};
|
||||
var keys = new Dictionary<string, uint>(StringComparer.Ordinal);
|
||||
var valueIndex = new Dictionary<string, uint>(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<uint>(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<string, uint> keys,
|
||||
Dictionary<string, uint> values,
|
||||
List<uint> 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<string, uint> keys,
|
||||
Dictionary<string, uint> values,
|
||||
List<uint> 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<string, uint> keys,
|
||||
Dictionary<string, uint> values,
|
||||
List<uint> 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<string, uint> 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<string, uint> 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;
|
||||
}
|
||||
}
|
||||
@@ -161,23 +161,79 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger<SqliteRoadGra
|
||||
break;
|
||||
}
|
||||
|
||||
items.Add(new RoadGraphEdge(
|
||||
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)));
|
||||
items.Add(ReadEdge(reader, id));
|
||||
}
|
||||
|
||||
return new RoadGraphPage<RoadGraphEdge>(items, next);
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<RoadGraphEdge>> QueryEdgesInBoundsAsync(
|
||||
string extractId,
|
||||
RoadGraphBounds bounds,
|
||||
IReadOnlyList<string>? 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<RoadGraphEdge>(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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
+132
-189
@@ -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<string, string> = {
|
||||
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<GraphMeta | null>(null);
|
||||
const [graphEdgeCount, setGraphEdgeCount] = useState(0);
|
||||
const [graphNodeCount, setGraphNodeCount] = useState(0);
|
||||
const [graphBbox, setGraphBbox] = useState("");
|
||||
const [graphSample, setGraphSample] = useState<GraphEdge[]>([]);
|
||||
const [graphDrawn, setGraphDrawn] = useState(0);
|
||||
const [graphEnabled, setGraphEnabled] = useState(false);
|
||||
const [access, setAccess] = useState<Access>(() => {
|
||||
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<SourceItem[]>([]);
|
||||
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<GraphMeta>(graphMetaUrl(access, graphSource.id)),
|
||||
fetchJson<GraphPage<GraphNode>>(graphNodesUrl(access, graphSource.id, bbox, 0, 5000)),
|
||||
fetchJson<GraphPage<GraphEdge>>(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<GraphMeta>(graphMetaUrl(access, graphSources[0].id));
|
||||
const waitStyle = () =>
|
||||
new Promise<void>((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() {
|
||||
<summary>Граф дорог</summary>
|
||||
<div className="graph-panel">
|
||||
<p className="graph-panel__hint">
|
||||
Берёт bbox текущего viewport (≤ 2°) и первый выбранный округ
|
||||
{graphSource ? ` («${graphSource.name}»)` : ""}. Нажми «Проверить viewport» — рёбра
|
||||
рисуются оранжевым поверх карты. На широком зуме сначала жми «Москва».
|
||||
Векторные тайлы <code>graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code>
|
||||
{graphSources.length > 0
|
||||
? ` — ${graphSources.map((item) => `«${item.name}»`).join(", ")}`
|
||||
: graphSource
|
||||
? ` («${graphSource.name}»)`
|
||||
: ""}
|
||||
. Слой <code>roads</code>, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}. Оранжевые линии поверх OSM.
|
||||
</p>
|
||||
<div className="graph-panel__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--accent"
|
||||
disabled={graphLoading || !personal}
|
||||
disabled={graphLoading || !personal || graphEnabled}
|
||||
onClick={() => void loadGraph()}
|
||||
>
|
||||
{graphLoading ? "Загрузка…" : "Проверить viewport"}
|
||||
{graphLoading ? "Подключение…" : "Показать граф"}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={!graphMeta && graphEdgeCount === 0} onClick={clearGraph}>
|
||||
<button type="button" className="btn" disabled={!graphEnabled} onClick={clearGraph}>
|
||||
Снять слой
|
||||
</button>
|
||||
</div>
|
||||
@@ -688,18 +652,8 @@ export function App() {
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>В bbox</dt>
|
||||
<dd>
|
||||
{formatNumber(graphNodeCount)} узл. · {formatNumber(graphEdgeCount)} рёбер
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Нарисовано</dt>
|
||||
<dd>{formatNumber(graphDrawn)} линий</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>bbox</dt>
|
||||
<dd className="graph-panel__bbox">{graphBbox}</dd>
|
||||
<dt>Слои</dt>
|
||||
<dd>{graphEnabled ? `${graphSources.length} vector source` : "выкл"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Собран</dt>
|
||||
@@ -707,17 +661,6 @@ export function App() {
|
||||
</div>
|
||||
</dl>
|
||||
) : null}
|
||||
{graphSample.length > 0 ? (
|
||||
<ul className="graph-panel__sample">
|
||||
{graphSample.map((edge) => (
|
||||
<li key={edge.id}>
|
||||
<span>{edge.highway}</span>
|
||||
<span>{edge.name || `${edge.fromId}→${edge.toId}`}</span>
|
||||
<span>{Math.round(edge.lengthM)} м</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
</details>
|
||||
</aside>
|
||||
|
||||
@@ -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)}`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<figure className="graph-copy">
|
||||
<figure className={code ? "graph-copy graph-copy--code" : "graph-copy"}>
|
||||
<figcaption>
|
||||
<span>{label}</span>
|
||||
<button
|
||||
@@ -91,13 +92,19 @@ export function GraphPage() {
|
||||
|
||||
const urls = useMemo(() => {
|
||||
const id = source?.id ?? "central-fed-district";
|
||||
const q = `token=${encodeURIComponent(activeToken)}`;
|
||||
return {
|
||||
meta: `${origin}/u/${slug}/graph/${id}?${q}`,
|
||||
nodes: `${origin}/u/${slug}/graph/${id}/nodes?bbox=${bbox}&${q}`,
|
||||
edges: `${origin}/u/${slug}/graph/${id}/edges?bbox=${bbox}&limit=50&${q}`
|
||||
};
|
||||
}, [origin, slug, source?.id, bbox, activeToken]);
|
||||
const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${id}&token=${encodeURIComponent(activeToken)}`;
|
||||
const lon = source?.center?.[0] ?? 37.6173;
|
||||
const lat = source?.center?.[1] ?? 55.7558;
|
||||
return buildGraphExamples({
|
||||
origin,
|
||||
slug,
|
||||
sourceId: id,
|
||||
token: activeToken,
|
||||
bbox,
|
||||
styleUrl,
|
||||
center: [lon, lat]
|
||||
});
|
||||
}, [origin, slug, source?.id, source?.center, bbox, activeToken]);
|
||||
|
||||
useEffect(() => {
|
||||
void api
|
||||
@@ -164,7 +171,7 @@ export function GraphPage() {
|
||||
<PageHeader
|
||||
eyebrow="Данные"
|
||||
title="Граф дорог"
|
||||
description="Лёгкий граф из OSM highway=* рядом с тайлами. Только персональный URL и токен."
|
||||
description="Лёгкий граф из OSM highway=* рядом с тайлами. Карта — через MVT. JSON bbox — точечная выборка."
|
||||
/>
|
||||
<Flash error={error} />
|
||||
|
||||
@@ -242,13 +249,41 @@ export function GraphPage() {
|
||||
) : null}
|
||||
</Section>
|
||||
|
||||
<Section title="URL">
|
||||
<Section
|
||||
title="URL"
|
||||
description="Подставьте token= из «Токены». MVT — на карту. JSON bbox — точечная выборка, сторона ≤ 2°."
|
||||
>
|
||||
<CopyField label="Метаданные" value={urls.meta} />
|
||||
<CopyField label="Узлы" value={urls.nodes} />
|
||||
<CopyField label="Рёбра" value={urls.edges} />
|
||||
<p className="graph-page__hint">
|
||||
Примеры кода и контракт ответа — в <Link to="/guides">Инструкциях</Link>, блок «Граф дорог».
|
||||
</p>
|
||||
<CopyField label="Тайлы MVT" value={urls.tiles} />
|
||||
<CopyField label="TileJSON" value={urls.tilejson} />
|
||||
<CopyField label="Узлы (bbox ≤ 2°)" value={urls.nodes} />
|
||||
<CopyField label="Рёбра (bbox ≤ 2°)" value={urls.edges} />
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Примеры"
|
||||
description={
|
||||
<>
|
||||
Код уже с выбранным округом и токеном. Слой MapLibre: <code>source-layer: roads</code>, minzoom 6, maxzoom
|
||||
14. Поля: <code>highway</code>, <code>name</code>, <code>oneway</code>, <code>length_m</code>. Пошагово — в{" "}
|
||||
<Link to="/guides">Инструкциях</Link>, шаг 5.
|
||||
</>
|
||||
}
|
||||
>
|
||||
<ul className="graph-page__list">
|
||||
<li>Добавляйте source после load / idle — иначе MapLibre отбросит слой при смене стиля.</li>
|
||||
<li>
|
||||
z 6–8: motorway/trunk; z 9–10: + primary; z 11–12: + secondary/tertiary; z 13+: все классы, до 8000 рёбер на
|
||||
тайл.
|
||||
</li>
|
||||
<li>Геометрия — прямая между вершинами графа, не исходная полилиния OSM.</li>
|
||||
</ul>
|
||||
<CopyField code label="MapLibre: слой поверх стиля" value={urls.mapLibre} />
|
||||
<CopyField code label="HTML: карта + граф" value={urls.html} />
|
||||
<CopyField code label="React: карта + граф" value={urls.react} />
|
||||
<CopyField code label="curl одного тайла (центр округа, z14)" value={urls.curlTile} />
|
||||
<CopyField code label="fetch + пагинация JSON" value={urls.fetchEdges} />
|
||||
<CopyField code label="curl JSON рёбер" value={urls.curlEdges} />
|
||||
</Section>
|
||||
|
||||
{meta ? (
|
||||
|
||||
@@ -18,6 +18,22 @@
|
||||
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
|
||||
}
|
||||
|
||||
.graph-page__list {
|
||||
margin: 0 0 var(--space-4);
|
||||
padding-left: 1.2rem;
|
||||
color: var(--secondary-label);
|
||||
font-size: var(--text-subhead);
|
||||
}
|
||||
|
||||
.graph-page__list li + li {
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.graph-page .section__desc code {
|
||||
font-family: ui-monospace, "Cascadia Mono", Consolas, monospace;
|
||||
font-size: 0.92em;
|
||||
}
|
||||
|
||||
.graph-copy {
|
||||
margin: 0 0 var(--space-3);
|
||||
border-radius: var(--radius-lg);
|
||||
@@ -58,6 +74,10 @@
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.graph-copy--code pre {
|
||||
word-break: normal;
|
||||
}
|
||||
|
||||
.graph-meta {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
export function sampleTile(lon: number, lat: number, z = 14): { z: number; x: number; y: number } {
|
||||
const n = 2 ** z;
|
||||
const clamped = Math.min(85.05112878, Math.max(-85.05112878, lat));
|
||||
const latRad = (clamped * Math.PI) / 180;
|
||||
const x = Math.floor(((lon + 180) / 360) * n);
|
||||
const y = Math.floor(((1 - Math.log(Math.tan(latRad) + 1 / Math.cos(latRad)) / Math.PI) / 2) * n);
|
||||
return { z, x, y };
|
||||
}
|
||||
|
||||
export type GraphExampleInput = {
|
||||
origin: string;
|
||||
slug: string;
|
||||
sourceId: string;
|
||||
token: string;
|
||||
bbox: string;
|
||||
styleUrl: string;
|
||||
center: [number, number];
|
||||
};
|
||||
|
||||
export type GraphExamples = {
|
||||
tiles: string;
|
||||
tilejson: string;
|
||||
meta: string;
|
||||
nodes: string;
|
||||
edges: string;
|
||||
sampleTileUrl: string;
|
||||
mapLibre: string;
|
||||
html: string;
|
||||
react: string;
|
||||
fetchEdges: string;
|
||||
curlTile: string;
|
||||
curlEdges: string;
|
||||
};
|
||||
|
||||
export function buildGraphExamples(input: GraphExampleInput): GraphExamples {
|
||||
const { origin, slug, sourceId, bbox, styleUrl, center } = input;
|
||||
const q = `token=${encodeURIComponent(input.token)}`;
|
||||
const base = `${origin}/u/${slug}/graph/${sourceId}`;
|
||||
const path = `/u/${slug}/graph/${sourceId}`;
|
||||
const tiles = `${base}/{z}/{x}/{y}.pbf?${q}`;
|
||||
const tilejson = `${base}/tiles.json?${q}`;
|
||||
const meta = `${base}?${q}`;
|
||||
const nodes = `${base}/nodes?bbox=${bbox}&${q}`;
|
||||
const edges = `${base}/edges?bbox=${bbox}&limit=50&${q}`;
|
||||
const xyz = sampleTile(center[0], center[1]);
|
||||
const sampleTileUrl = `${base}/${xyz.z}/${xyz.x}/${xyz.y}.pbf?${q}`;
|
||||
|
||||
const mapLibre = `map.on("load", () => {
|
||||
map.addSource("road-graph", {
|
||||
type: "vector",
|
||||
tiles: ["${tiles}"],
|
||||
minzoom: 6,
|
||||
maxzoom: 14
|
||||
});
|
||||
map.addLayer({
|
||||
id: "road-graph-casing",
|
||||
type: "line",
|
||||
source: "road-graph",
|
||||
"source-layer": "roads",
|
||||
paint: {
|
||||
"line-color": "#1a1208",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1.6, 14, 6],
|
||||
"line-opacity": 0.85
|
||||
}
|
||||
});
|
||||
map.addLayer({
|
||||
id: "road-graph",
|
||||
type: "line",
|
||||
source: "road-graph",
|
||||
"source-layer": "roads",
|
||||
paint: {
|
||||
"line-color": "#ffb45a",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 14, 3.6]
|
||||
}
|
||||
});
|
||||
});`;
|
||||
|
||||
const indented = mapLibre
|
||||
.split("\n")
|
||||
.map((line) => (line.length > 0 ? ` ${line}` : line))
|
||||
.join("\n");
|
||||
|
||||
const html = `<link href="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.css" rel="stylesheet" />
|
||||
<script src="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.js"></script>
|
||||
<div id="map" style="width:100%;height:420px"></div>
|
||||
<script>
|
||||
const map = new maplibregl.Map({
|
||||
container: "map",
|
||||
style: "${styleUrl}",
|
||||
center: [${center[0]}, ${center[1]}],
|
||||
zoom: 12
|
||||
});
|
||||
${indented}
|
||||
</script>`;
|
||||
|
||||
const react = `import maplibregl from "maplibre-gl";
|
||||
import "maplibre-gl/dist/maplibre-gl.css";
|
||||
|
||||
const map = new maplibregl.Map({
|
||||
container: "map",
|
||||
style: "${styleUrl}",
|
||||
center: [${center[0]}, ${center[1]}],
|
||||
zoom: 12
|
||||
});
|
||||
|
||||
${mapLibre}`;
|
||||
|
||||
const fetchEdges = `const token = "${input.token}";
|
||||
const source = "${sourceId}";
|
||||
const bbox = "${bbox}"; // minLon,minLat,maxLon,maxLat, сторона ≤ 2°
|
||||
|
||||
const meta = await fetch(\`${path}?token=\${token}\`).then((r) => r.json());
|
||||
// { extractId, nodeCount, edgeCount, bounds, builtAt, links: { tiles, tilejson, nodes, edges } }
|
||||
|
||||
let after = 0;
|
||||
const edges = [];
|
||||
for (;;) {
|
||||
const page = await fetch(
|
||||
\`${path}/edges?bbox=\${bbox}&after=\${after}&limit=5000&token=\${token}\`
|
||||
).then((r) => r.json());
|
||||
edges.push(...page.items);
|
||||
if (page.nextAfter == null) break;
|
||||
after = page.nextAfter;
|
||||
}
|
||||
// items[]: { id, fromId, toId, highway, name, oneway, lengthM, fromLon, fromLat, toLon, toLat }
|
||||
// oneway=false → ребро двустороннее`;
|
||||
|
||||
return {
|
||||
tiles,
|
||||
tilejson,
|
||||
meta,
|
||||
nodes,
|
||||
edges,
|
||||
sampleTileUrl,
|
||||
mapLibre,
|
||||
html,
|
||||
react,
|
||||
fetchEdges,
|
||||
curlTile: `curl -sL "${sampleTileUrl}" -o graph-tile.pbf`,
|
||||
curlEdges: `curl -s "${edges}"`
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { Link } from "react-router-dom";
|
||||
import { api, getPreviewToken, setPreviewToken, type SourceItem } from "../../api";
|
||||
import { Button, Flash, PageHeader } from "../../components/ui";
|
||||
import { useAuth } from "../auth/AuthContext";
|
||||
import { buildGraphExamples } from "../graph/graphExamples";
|
||||
import { StylePreview } from "../styles/StylePreview";
|
||||
import "./guides.css";
|
||||
|
||||
@@ -39,6 +40,8 @@ export function GuidesPage() {
|
||||
const origin = window.location.origin;
|
||||
const slug = user?.slug ?? "{slug}";
|
||||
const tokenSuffix = token ? `token=${token}` : "token=ts_…";
|
||||
const centerLon = sources[0]?.center?.[0] ?? 37.6173;
|
||||
const centerLat = sources[0]?.center?.[1] ?? 55.7558;
|
||||
|
||||
useEffect(() => {
|
||||
void api
|
||||
@@ -49,9 +52,19 @@ export function GuidesPage() {
|
||||
|
||||
const styleUrl = `${origin}/u/${slug}/styles/osm-bright?source=${source}&${tokenSuffix}`;
|
||||
const tilesUrl = `${origin}/u/${slug}/tiles/${source}/{z}/{x}/{y}.pbf?${tokenSuffix}`;
|
||||
const graphUrl = `${origin}/u/${slug}/graph/${source}?${tokenSuffix}`;
|
||||
const graphNodesUrl = `${origin}/u/${slug}/graph/${source}/nodes?bbox=37.5,55.7,37.7,55.8&${tokenSuffix}`;
|
||||
const graphEdgesUrl = `${origin}/u/${slug}/graph/${source}/edges?bbox=37.5,55.7,37.7,55.8&limit=100&${tokenSuffix}`;
|
||||
const graph = useMemo(
|
||||
() =>
|
||||
buildGraphExamples({
|
||||
origin,
|
||||
slug,
|
||||
sourceId: source,
|
||||
token: token || "ts_…",
|
||||
bbox: "37.5,55.7,37.7,55.8",
|
||||
styleUrl,
|
||||
center: [centerLon, centerLat]
|
||||
}),
|
||||
[origin, slug, source, token, styleUrl, centerLon, centerLat]
|
||||
);
|
||||
|
||||
const html = useMemo(
|
||||
() => `<link href="https://unpkg.com/maplibre-gl@5.6.1/dist/maplibre-gl.css" rel="stylesheet" />
|
||||
@@ -81,31 +94,6 @@ const map = new maplibregl.Map({
|
||||
[styleUrl]
|
||||
);
|
||||
|
||||
const graphFetch = useMemo(
|
||||
() => `const token = "ts_…";
|
||||
const source = "${source}";
|
||||
const bbox = "37.5,55.7,37.7,55.8"; // minLon,minLat,maxLon,maxLat, сторона ≤ 2°
|
||||
|
||||
const meta = await fetch(\`/u/${slug}/graph/\${source}?token=\${token}\`).then((r) => r.json());
|
||||
// { extractId, nodeCount, edgeCount, bounds, builtAt, links }
|
||||
|
||||
let after = 0;
|
||||
const edges = [];
|
||||
for (;;) {
|
||||
const page = await fetch(
|
||||
\`/u/${slug}/graph/\${source}/edges?bbox=\${bbox}&after=\${after}&limit=5000&token=\${token}\`
|
||||
).then((r) => r.json());
|
||||
edges.push(...page.items);
|
||||
if (page.nextAfter == null) break;
|
||||
after = page.nextAfter;
|
||||
}
|
||||
// page.items[]: { id, fromId, toId, highway, name, oneway, lengthM }
|
||||
// oneway=false → ребро двустороннее (ездить можно в обе стороны)`,
|
||||
[slug, source]
|
||||
);
|
||||
|
||||
const graphCurl = `curl -s "${graphEdgesUrl}"`;
|
||||
|
||||
return (
|
||||
<div className="guides">
|
||||
<PageHeader
|
||||
@@ -164,12 +152,30 @@ for (;;) {
|
||||
</p>
|
||||
</li>
|
||||
<li>
|
||||
<strong>5. Граф дорог</strong>
|
||||
<strong>5. Граф дорог на карте</strong>
|
||||
<p>
|
||||
На sync из того же PBF собирается SQLite-граф (<code>highway</code> motorway…service): узлы — перекрёстки,
|
||||
рёбра — сегменты с <code>lengthM</code> и <code>oneway</code>. Смотреть и дергать API — в разделе{" "}
|
||||
<Link to="/graph">Граф</Link>.
|
||||
На sync из того же PBF собирается SQLite-граф (узлы — перекрёстки, рёбра — сегменты{" "}
|
||||
<code>highway=motorway…service</code>). На карту его кладут вторым vector source, как OSM-тайлы: не JSON
|
||||
bbox. Готовые URL и превью — в разделе <Link to="/graph">Граф</Link>.
|
||||
</p>
|
||||
<ul className="guide-steps__notes">
|
||||
<li>
|
||||
После <code>map.on("load")</code> (или после <code>setStyle</code> → <code>idle</code>) добавьте
|
||||
source с шаблоном <code>/u/{"{slug}"}/graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf?token=</code>.
|
||||
</li>
|
||||
<li>
|
||||
Слой MapLibre: <code>type: line</code>, <code>source-layer: roads</code>, minzoom 6, maxzoom 14.
|
||||
Поля: <code>highway</code>, <code>name</code>, <code>oneway</code>, <code>length_m</code>.
|
||||
</li>
|
||||
<li>
|
||||
На мелком зуме сервер отдаёт только крупные дороги (z≤8 motorway/trunk, затем primary, secondary). JSON{" "}
|
||||
<code>/nodes</code> и <code>/edges</code> — точечная выборка, сторона bbox ≤ 2°.
|
||||
</li>
|
||||
<li>
|
||||
Нет файла графа → 404. Дождитесь sync или <code>POST /api/v1/sync/{"{id}"}</code> при{" "}
|
||||
<code>BuildRoadGraph=true</code>.
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
@@ -183,14 +189,20 @@ for (;;) {
|
||||
|
||||
<h2 className="guides__h">Граф дорог</h2>
|
||||
<p className="guides__lead">
|
||||
Только с токеном. Выгрузка всего округа целиком запрещена: всегда указывайте <code>bbox</code> (сторона ≤ 2°),
|
||||
дальше листайте через <code>after</code> / <code>nextAfter</code>.
|
||||
Тайлы графа — как OSM: <code>/graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code>, слой <code>roads</code>.
|
||||
Ниже примеры уже с вашим slug, округом и токеном. Геометрия ребра — прямая между вершинами, не полилиния OSM.
|
||||
</p>
|
||||
<CopyBlock label="Метаданные" value={graphUrl} />
|
||||
<CopyBlock label="Узлы в bbox" value={graphNodesUrl} />
|
||||
<CopyBlock label="Рёбра в bbox" value={graphEdgesUrl} />
|
||||
<CopyBlock label="curl" value={graphCurl} />
|
||||
<CopyBlock label="fetch + пагинация" value={graphFetch} />
|
||||
<CopyBlock label="Тайлы MVT" value={graph.tiles} />
|
||||
<CopyBlock label="TileJSON" value={graph.tilejson} />
|
||||
<CopyBlock label="MapLibre: слой поверх стиля" value={graph.mapLibre} />
|
||||
<CopyBlock label="HTML: карта + граф" value={graph.html} />
|
||||
<CopyBlock label="React: карта + граф" value={graph.react} />
|
||||
<CopyBlock label="curl одного тайла (центр округа, z14)" value={graph.curlTile} />
|
||||
<CopyBlock label="Метаданные" value={graph.meta} />
|
||||
<CopyBlock label="Узлы в bbox" value={graph.nodes} />
|
||||
<CopyBlock label="Рёбра в bbox" value={graph.edges} />
|
||||
<CopyBlock label="curl JSON рёбер" value={graph.curlEdges} />
|
||||
<CopyBlock label="fetch + пагинация JSON" value={graph.fetchEdges} />
|
||||
|
||||
<h2 className="guides__h">HTML</h2>
|
||||
<CopyBlock label="Минимальная страница" value={html} />
|
||||
|
||||
@@ -62,6 +62,24 @@
|
||||
font-size: var(--text-footnote);
|
||||
}
|
||||
|
||||
.guide-steps__notes {
|
||||
margin: 0;
|
||||
padding-left: 1.15rem;
|
||||
color: var(--secondary-label);
|
||||
font-size: var(--text-subhead);
|
||||
}
|
||||
|
||||
.guide-steps__notes li {
|
||||
padding: 0 0 6px;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.guide-steps__notes li:last-child {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
.guide-code {
|
||||
margin: 0 var(--gutter) var(--space-4);
|
||||
border-radius: var(--radius-xl);
|
||||
|
||||
Reference in New Issue
Block a user