fix(graph): add all roads
This commit is contained in:
@@ -61,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). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (на мелком зуме только крупные highway). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`.
|
||||
Публичные `/api/v1/tiles` и `/api/v1/styles` закрыты (401). Граф — только по токену. MVT графа: слой `roads`, z 6–14 (ниже z12 только крупные highway, с z12 все улицы; полилиния после пересборки графа). JSON `bbox=minLon,minLat,maxLon,maxLat`, сторона ≤ 2°. Выключается: `TileServer:BuildRoadGraph=false`.
|
||||
|
||||
## Несколько регионов
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# web-demo tiled graph in style
|
||||
|
||||
Date: 2026-09-21
|
||||
|
||||
## What
|
||||
|
||||
web-demo no longer waits on JSON bbox / a «Показать граф» click. When the checkbox is on (default), graph MVT sources (`/u/{slug}/graph/{id}/{z}/{x}/{y}.pbf`, layer `roads`) are injected into the MapLibre style JSON the same way OSM tiles are. Toggle reloads the style. `rewriteServiceUrl` keeps `{z}/{x}/{y}` unencoded. Graph tile 404s stay in the graph HUD, not the map banner.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Graph polylines + all streets from z12
|
||||
|
||||
Date: 2026-09-21
|
||||
|
||||
## Why the overlay looked wrong
|
||||
|
||||
Crooked chords: edges were vertex-to-vertex (intersections only), no OSM shape nodes.
|
||||
Only highways at z12–13: zoom filter kept residential out until z13, and `ORDER BY length_m DESC LIMIT 8000` dropped short streets even then.
|
||||
|
||||
## Change
|
||||
|
||||
- Builder stores `edges.geom` (lon/lat polyline). Encoder clips that LineString. Old sqlite without `geom` still draws chords — resync required for curves.
|
||||
- All highway classes from z12 (residential/service included). Cap 40k features, order by id not length.
|
||||
@@ -63,7 +63,7 @@ public sealed class RoadGraphTileService(
|
||||
try
|
||||
{
|
||||
edges = await store
|
||||
.QueryEdgesInBoundsAsync(extractId, bounds, highways, RoadGraphZoomPolicy.MaxFeaturesPerTile, ct)
|
||||
.QueryEdgesInBoundsAsync(extractId, bounds, highways, RoadGraphZoomPolicy.MaxFeaturesForZoom(tile.Z), ct)
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -118,7 +118,7 @@ public sealed class RoadGraphTileService(
|
||||
[
|
||||
new VectorLayerJson(
|
||||
"roads",
|
||||
"OSM highway segments as vertex-to-vertex edges",
|
||||
"OSM highway polylines (shape nodes between intersections)",
|
||||
RoadGraphZoomPolicy.MinZoom,
|
||||
RoadGraphZoomPolicy.MaxZoom,
|
||||
fields)
|
||||
|
||||
@@ -5,7 +5,6 @@ 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 =
|
||||
@@ -22,15 +21,23 @@ public static class RoadGraphZoomPolicy
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Low zooms keep only major highways so a 2°+ tile does not pull the whole graph.
|
||||
/// Null means no filter (all classes).
|
||||
/// Low zooms keep only major highways so a large tile does not pull the whole graph.
|
||||
/// Null means no filter (residential/service included). All streets from z12.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string>? HighwaysForZoom(int z)
|
||||
=> z switch
|
||||
{
|
||||
<= 8 => Trunk,
|
||||
<= 10 => Primary,
|
||||
<= 12 => Secondary,
|
||||
<= 11 => Secondary,
|
||||
_ => null
|
||||
};
|
||||
|
||||
public static int MaxFeaturesForZoom(int z)
|
||||
=> z switch
|
||||
{
|
||||
<= 10 => 8_000,
|
||||
<= 11 => 16_000,
|
||||
_ => 40_000
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,6 +11,8 @@ public sealed record RoadGraphMetadata(
|
||||
|
||||
public sealed record RoadGraphNode(long Id, double Lon, double Lat);
|
||||
|
||||
public sealed record RoadGraphPoint(double Lon, double Lat);
|
||||
|
||||
public sealed record RoadGraphEdge(
|
||||
long Id,
|
||||
long FromId,
|
||||
@@ -22,6 +24,7 @@ public sealed record RoadGraphEdge(
|
||||
double FromLon,
|
||||
double FromLat,
|
||||
double ToLon,
|
||||
double ToLat);
|
||||
double ToLat,
|
||||
IReadOnlyList<RoadGraphPoint>? Geometry = null);
|
||||
|
||||
public sealed record RoadGraphPage<T>(IReadOnlyList<T> Items, long? NextAfter);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
using System.Buffers.Binary;
|
||||
using TileServer.Domain.Graph;
|
||||
|
||||
namespace TileServer.Infrastructure.Graph;
|
||||
|
||||
internal static class GraphGeometry
|
||||
{
|
||||
public static byte[] Pack(IReadOnlyList<RoadGraphPoint> points)
|
||||
{
|
||||
var bytes = new byte[points.Count * 16];
|
||||
for (var i = 0; i < points.Count; i++)
|
||||
{
|
||||
var span = bytes.AsSpan(i * 16);
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(span, points[i].Lon);
|
||||
BinaryPrimitives.WriteDoubleLittleEndian(span[8..], points[i].Lat);
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
public static IReadOnlyList<RoadGraphPoint>? Unpack(byte[]? bytes)
|
||||
{
|
||||
if (bytes is null || bytes.Length < 32 || bytes.Length % 16 != 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var count = bytes.Length / 16;
|
||||
var points = new RoadGraphPoint[count];
|
||||
for (var i = 0; i < count; i++)
|
||||
{
|
||||
var span = bytes.AsSpan(i * 16);
|
||||
points[i] = new RoadGraphPoint(
|
||||
BinaryPrimitives.ReadDoubleLittleEndian(span),
|
||||
BinaryPrimitives.ReadDoubleLittleEndian(span[8..]));
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,13 @@ using OsmSharp.Streams;
|
||||
using OsmSharp.Tags;
|
||||
using TileServer.Application.Graph;
|
||||
using TileServer.Domain.Extracts;
|
||||
using TileServer.Domain.Graph;
|
||||
|
||||
namespace TileServer.Infrastructure.Graph;
|
||||
|
||||
/// <summary>
|
||||
/// Two-pass PBF scan: highway ways → degree map + packed node refs; nodes → coords;
|
||||
/// then collapse chains between intersections into edges with Haversine length.
|
||||
/// then collapse chains between intersections into edges with Haversine length and packed polyline geometry.
|
||||
/// </summary>
|
||||
public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> logger) : IRoadGraphBuilder
|
||||
{
|
||||
@@ -248,10 +249,12 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
highway TEXT NOT NULL,
|
||||
name TEXT,
|
||||
oneway INTEGER NOT NULL,
|
||||
length_m REAL NOT NULL
|
||||
length_m REAL NOT NULL,
|
||||
geom BLOB
|
||||
);
|
||||
CREATE INDEX edges_from ON edges(from_id);
|
||||
CREATE INDEX edges_to ON edges(to_id);
|
||||
CREATE INDEX edges_highway ON edges(highway);
|
||||
CREATE INDEX nodes_lonlat ON nodes(lon, lat);
|
||||
""";
|
||||
await schema.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
@@ -279,8 +282,8 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
insertEdge.Transaction = outTx;
|
||||
insertEdge.CommandText =
|
||||
"""
|
||||
INSERT INTO edges (id, from_id, to_id, highway, name, oneway, length_m)
|
||||
VALUES ($id, $from, $to, $highway, $name, $oneway, $length);
|
||||
INSERT INTO edges (id, from_id, to_id, highway, name, oneway, length_m, geom)
|
||||
VALUES ($id, $from, $to, $highway, $name, $oneway, $length, $geom);
|
||||
""";
|
||||
var eId = insertEdge.Parameters.Add("$id", SqliteType.Integer);
|
||||
var eFrom = insertEdge.Parameters.Add("$from", SqliteType.Integer);
|
||||
@@ -289,6 +292,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
var eName = insertEdge.Parameters.Add("$name", SqliteType.Text);
|
||||
var eOneway = insertEdge.Parameters.Add("$oneway", SqliteType.Integer);
|
||||
var eLength = insertEdge.Parameters.Add("$length", SqliteType.Real);
|
||||
var eGeom = insertEdge.Parameters.Add("$geom", SqliteType.Blob);
|
||||
|
||||
await using (var readWays = ways.CreateCommand())
|
||||
{
|
||||
@@ -309,6 +313,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
long? segmentFrom = null;
|
||||
double segmentLength = 0;
|
||||
(double Lon, double Lat)? prevCoord = null;
|
||||
var shape = new List<RoadGraphPoint>(8);
|
||||
|
||||
for (var i = 0; i < nodeIds.Length; i++)
|
||||
{
|
||||
@@ -318,6 +323,7 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
segmentFrom = null;
|
||||
prevCoord = null;
|
||||
segmentLength = 0;
|
||||
shape.Clear();
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -333,9 +339,15 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
{
|
||||
vertexIds.Add(nodeId);
|
||||
ExpandBounds(ref minLon, ref minLat, ref maxLon, ref maxLat, coord.Lon, coord.Lat);
|
||||
if (segmentFrom is long fromId && fromId != nodeId && segmentLength > 0)
|
||||
if (segmentFrom is long fromId && fromId != nodeId && segmentLength > 0 && shape.Count >= 1)
|
||||
{
|
||||
shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat));
|
||||
var (from, to, onewayFlag) = NormalizeDirection(fromId, nodeId, onewayCode);
|
||||
if (from != fromId)
|
||||
{
|
||||
shape.Reverse();
|
||||
}
|
||||
|
||||
eId.Value = ++edgeId;
|
||||
eFrom.Value = from;
|
||||
eTo.Value = to;
|
||||
@@ -343,11 +355,18 @@ public sealed class OsmSharpRoadGraphBuilder(ILogger<OsmSharpRoadGraphBuilder> l
|
||||
eName.Value = name is null ? DBNull.Value : name;
|
||||
eOneway.Value = onewayFlag ? 1 : 0;
|
||||
eLength.Value = segmentLength;
|
||||
eGeom.Value = GraphGeometry.Pack(shape);
|
||||
await insertEdge.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
segmentFrom = nodeId;
|
||||
segmentLength = 0;
|
||||
shape.Clear();
|
||||
shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat));
|
||||
}
|
||||
else if (segmentFrom is not null)
|
||||
{
|
||||
shape.Add(new RoadGraphPoint(coord.Lon, coord.Lat));
|
||||
}
|
||||
|
||||
prevCoord = coord;
|
||||
|
||||
@@ -24,14 +24,8 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder
|
||||
|
||||
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)
|
||||
var paths = ProjectAndClip(edge, tile);
|
||||
if (paths.Count == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -51,7 +45,7 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder
|
||||
Id = (ulong)Math.Max(0, edge.Id),
|
||||
Type = MvtCodec.LineString,
|
||||
Tags = tags,
|
||||
Geometry = MvtCodec.EncodeGeometry([[a, b]], close: false)
|
||||
Geometry = MvtCodec.EncodeGeometry(paths, close: false)
|
||||
});
|
||||
}
|
||||
|
||||
@@ -59,6 +53,67 @@ public sealed class RoadGraphMvtEncoder : IRoadGraphMvtEncoder
|
||||
return MvtCodec.EncodeGzip(mvt);
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<IReadOnlyList<(int X, int Y)>> ProjectAndClip(RoadGraphEdge edge, TileCoordinate tile)
|
||||
{
|
||||
var points = edge.Geometry is { Count: >= 2 }
|
||||
? edge.Geometry
|
||||
: new[] { new RoadGraphPoint(edge.FromLon, edge.FromLat), new RoadGraphPoint(edge.ToLon, edge.ToLat) };
|
||||
var pixels = new List<(int X, int Y)>(points.Count);
|
||||
foreach (var point in points)
|
||||
{
|
||||
pixels.Add(tile.ToTilePixels(point.Lon, point.Lat, Extent));
|
||||
}
|
||||
|
||||
return ClipPolyline(pixels);
|
||||
}
|
||||
|
||||
internal static IReadOnlyList<IReadOnlyList<(int X, int Y)>> ClipPolyline(IReadOnlyList<(int X, int Y)> pixels)
|
||||
{
|
||||
var paths = new List<IReadOnlyList<(int X, int Y)>>();
|
||||
if (pixels.Count < 2)
|
||||
{
|
||||
return paths;
|
||||
}
|
||||
|
||||
var current = new List<(int X, int Y)>();
|
||||
for (var i = 1; i < pixels.Count; i++)
|
||||
{
|
||||
if (!ClipSegment(pixels[i - 1], pixels[i], out var a, out var b))
|
||||
{
|
||||
Flush(paths, current);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current.Count == 0)
|
||||
{
|
||||
current.Add(a);
|
||||
}
|
||||
else if (current[^1] != a)
|
||||
{
|
||||
Flush(paths, current);
|
||||
current.Add(a);
|
||||
}
|
||||
|
||||
if (current[^1] != b)
|
||||
{
|
||||
current.Add(b);
|
||||
}
|
||||
}
|
||||
|
||||
Flush(paths, current);
|
||||
return paths;
|
||||
}
|
||||
|
||||
private static void Flush(List<IReadOnlyList<(int X, int Y)>> paths, List<(int X, int Y)> current)
|
||||
{
|
||||
if (current.Count >= 2)
|
||||
{
|
||||
paths.Add(current.ToArray());
|
||||
}
|
||||
|
||||
current.Clear();
|
||||
}
|
||||
|
||||
internal static bool ClipSegment(
|
||||
(int X, int Y) from,
|
||||
(int X, int Y) to,
|
||||
|
||||
@@ -193,7 +193,7 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger<SqliteRoadGra
|
||||
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
|
||||
a.lon, a.lat, b.lon, b.lat{(HasGeometryColumn(connection) ? ", e.geom" : "")}
|
||||
FROM edges e
|
||||
INNER JOIN nodes a ON a.id = e.from_id
|
||||
INNER JOIN nodes b ON b.id = e.to_id
|
||||
@@ -201,7 +201,7 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger<SqliteRoadGra
|
||||
(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
|
||||
ORDER BY e.id
|
||||
LIMIT $limit;
|
||||
""";
|
||||
command.Parameters.AddWithValue("$minLon", bounds.MinLon);
|
||||
@@ -221,7 +221,14 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger<SqliteRoadGra
|
||||
}
|
||||
|
||||
private static RoadGraphEdge ReadEdge(SqliteDataReader reader, long id)
|
||||
=> new(
|
||||
{
|
||||
IReadOnlyList<RoadGraphPoint>? geometry = null;
|
||||
if (reader.FieldCount > 11 && !reader.IsDBNull(11))
|
||||
{
|
||||
geometry = GraphGeometry.Unpack((byte[])reader.GetValue(11));
|
||||
}
|
||||
|
||||
return new RoadGraphEdge(
|
||||
id,
|
||||
reader.GetInt64(1),
|
||||
reader.GetInt64(2),
|
||||
@@ -232,7 +239,16 @@ public sealed class SqliteRoadGraphStore(IDataPaths paths, ILogger<SqliteRoadGra
|
||||
reader.GetDouble(7),
|
||||
reader.GetDouble(8),
|
||||
reader.GetDouble(9),
|
||||
reader.GetDouble(10));
|
||||
reader.GetDouble(10),
|
||||
geometry);
|
||||
}
|
||||
|
||||
private static bool HasGeometryColumn(SqliteConnection connection)
|
||||
{
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "SELECT 1 FROM pragma_table_info('edges') WHERE name = 'geom' LIMIT 1;";
|
||||
return command.ExecuteScalar() is not null;
|
||||
}
|
||||
|
||||
private static SqliteConnection Open(string path)
|
||||
{
|
||||
|
||||
@@ -33,7 +33,7 @@ public sealed class RoadGraphTests
|
||||
[InlineData(6, "motorway")]
|
||||
[InlineData(8, "trunk")]
|
||||
[InlineData(10, "primary")]
|
||||
[InlineData(12, "tertiary")]
|
||||
[InlineData(11, "tertiary")]
|
||||
public void HighwaysForZoom_IncludesMajorClasses(int z, string highway)
|
||||
{
|
||||
var list = RoadGraphZoomPolicy.HighwaysForZoom(z);
|
||||
@@ -42,8 +42,8 @@ public sealed class RoadGraphTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HighwaysForZoom_AllClassesAtStreetLevel()
|
||||
=> Assert.Null(RoadGraphZoomPolicy.HighwaysForZoom(13));
|
||||
public void HighwaysForZoom_AllClassesFromZ12()
|
||||
=> Assert.Null(RoadGraphZoomPolicy.HighwaysForZoom(12));
|
||||
}
|
||||
|
||||
public sealed class RoadGraphMvtTests
|
||||
@@ -105,9 +105,36 @@ public sealed class RoadGraphMvtTests
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClipSegment_KeepsCrossingLine()
|
||||
public void Encode_Polyline_KeepsIntermediateVertex()
|
||||
{
|
||||
Assert.True(RoadGraphMvtEncoder.ClipSegment((-100, 100), (5000, 2000), out var a, out var b));
|
||||
Assert.NotEqual(a, b);
|
||||
var tile = TileCoordinate.FromLonLat(37.6173, 55.7558, 14);
|
||||
var edge = new RoadGraphEdge(
|
||||
1, 10, 11, "residential", null, false, 180,
|
||||
37.6173, 55.7558, 37.6190, 55.7568,
|
||||
[
|
||||
new RoadGraphPoint(37.6173, 55.7558),
|
||||
new RoadGraphPoint(37.6182, 55.7565),
|
||||
new RoadGraphPoint(37.6190, 55.7568)
|
||||
]);
|
||||
var data = new RoadGraphMvtEncoder().Encode([edge], tile);
|
||||
var decoded = MvtCodec.Decode(data);
|
||||
var feature = Assert.Single(Assert.Single(decoded.Layers).Features);
|
||||
var paths = MvtCodec.DecodeGeometry(feature.Geometry);
|
||||
var path = Assert.Single(paths);
|
||||
Assert.True(path.Count >= 3);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ClipPolyline_SplitsWhenLeavingTile()
|
||||
{
|
||||
var paths = RoadGraphMvtEncoder.ClipPolyline(
|
||||
[
|
||||
(100, 100),
|
||||
(200, 200),
|
||||
(8000, 8000),
|
||||
(100, 200)
|
||||
]);
|
||||
Assert.NotEmpty(paths);
|
||||
Assert.All(paths, path => Assert.True(path.Count >= 2));
|
||||
}
|
||||
}
|
||||
|
||||
+83
-137
@@ -88,73 +88,59 @@ function graphLineId(extractId: string): string {
|
||||
return `${GRAPH_PREFIX}-${extractId}-line`;
|
||||
}
|
||||
|
||||
function attachGraphTiles(map: MapLibreMap, access: Access, sources: SourceItem[]): string | null {
|
||||
if (!map.isStyleLoaded()) {
|
||||
return "Стиль карты ещё грузится — повтори через секунду.";
|
||||
function readyGraphSources(sources: SourceItem[]): SourceItem[] {
|
||||
return sources.filter((item) => item.graphReady !== false);
|
||||
}
|
||||
|
||||
clearGraphLayers(map);
|
||||
const ready = sources.filter((item) => item.graphReady !== false);
|
||||
function styleWithGraph(style: StyleSpecification, access: Access, extracts: SourceItem[]): StyleSpecification {
|
||||
const ready = readyGraphSources(extracts);
|
||||
if (ready.length === 0) {
|
||||
return "У выбранных округов граф ещё не собран. Синхронизируй extract.";
|
||||
return style;
|
||||
}
|
||||
|
||||
const sources = { ...style.sources };
|
||||
const layers = [...(style.layers ?? [])];
|
||||
for (const item of ready) {
|
||||
const sourceId = graphSourceId(item.id);
|
||||
map.addSource(sourceId, {
|
||||
sources[sourceId] = {
|
||||
type: "vector",
|
||||
tiles: [graphTilesUrl(access, item.id)],
|
||||
minzoom: GRAPH_MIN_ZOOM,
|
||||
maxzoom: GRAPH_MAX_ZOOM
|
||||
});
|
||||
map.addLayer({
|
||||
};
|
||||
layers.push(
|
||||
{
|
||||
id: graphCasingId(item.id),
|
||||
type: "line",
|
||||
source: sourceId,
|
||||
"source-layer": "roads",
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
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",
|
||||
layout: { "line-cap": "round", "line-join": "round" },
|
||||
paint: {
|
||||
"line-color": "#ffb45a",
|
||||
"line-width": ["interpolate", ["linear"], ["zoom"], 6, 1, 10, 2, 14, 3.6],
|
||||
"line-opacity": 1
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
return { ...style, sources, layers };
|
||||
}
|
||||
|
||||
function clearGraphLayers(map: MapLibreMap | null): void {
|
||||
if (!map) {
|
||||
return;
|
||||
}
|
||||
|
||||
const style = map.getStyle();
|
||||
if (!style) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const layer of [...(style.layers ?? [])]) {
|
||||
if (layer.id.startsWith(`${GRAPH_PREFIX}-`)) {
|
||||
map.removeLayer(layer.id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const id of Object.keys(style.sources ?? {})) {
|
||||
if (id.startsWith(`${GRAPH_PREFIX}-`)) {
|
||||
map.removeSource(id);
|
||||
}
|
||||
}
|
||||
function isGraphRequestError(message: string): boolean {
|
||||
return message.includes(GRAPH_PREFIX) || /\/graph\/[\w-]+\/\d+\/\d+\/\d+\.pbf/i.test(message);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
@@ -175,10 +161,9 @@ export function App() {
|
||||
const [gotoError, setGotoError] = useState("");
|
||||
const [banner, setBanner] = useState("");
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [graphLoading, setGraphLoading] = useState(false);
|
||||
const [graphError, setGraphError] = useState("");
|
||||
const [graphMeta, setGraphMeta] = useState<GraphMeta | null>(null);
|
||||
const [graphEnabled, setGraphEnabled] = useState(false);
|
||||
const [graphEnabled, setGraphEnabled] = useState(true);
|
||||
const [access, setAccess] = useState<Access>(() => {
|
||||
const stored = readAccess();
|
||||
persistAccess(stored);
|
||||
@@ -188,16 +173,13 @@ 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 graphSources = selectedSources.filter((item) => item.graphReady !== false);
|
||||
const graphSources = readyGraphSources(selectedSources);
|
||||
const graphSource = graphSources[0] ?? selectedSources[0] ?? sources[0];
|
||||
const graphKey = graphEnabled ? graphSources.map((item) => item.id).join(",") : "";
|
||||
|
||||
const updateHud = useCallback((map: MapLibreMap) => {
|
||||
const center = map.getCenter();
|
||||
@@ -254,12 +236,13 @@ export function App() {
|
||||
return;
|
||||
}
|
||||
|
||||
const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}`;
|
||||
const styleKey = `${access.slug}|${selectedSourceIds.join(",")}|${styleName}|${selectedSources.map((item) => `${item.status}:${item.builtAt ?? ""}`).join(";")}|g:${graphKey}`;
|
||||
if (mapRef.current && styleKeyRef.current === styleKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
const style = await fetchJson<StyleSpecification>(styleUrl(access, styleName, selectedSourceIds));
|
||||
const baseStyle = await fetchJson<StyleSpecification>(styleUrl(access, styleName, selectedSourceIds));
|
||||
const style = graphEnabled ? styleWithGraph(baseStyle, access, selectedSources) : baseStyle;
|
||||
const hashed = cameraFromHash();
|
||||
const center = hashed ? [hashed.lon, hashed.lat] : (source?.center ?? [37.6173, 55.7558]);
|
||||
const zoom = hashed ? hashed.zoom : 6;
|
||||
@@ -282,38 +265,27 @@ 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;
|
||||
if (message) {
|
||||
setBanner(message);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
if (isGraphRequestError(message)) {
|
||||
setGraphError(message);
|
||||
return;
|
||||
}
|
||||
setBanner(message);
|
||||
});
|
||||
mapRef.current = map;
|
||||
} else {
|
||||
mapRef.current.setStyle(style, { diff: false });
|
||||
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;
|
||||
const pending = selectedSources.find((item) => item.status !== "Ready");
|
||||
setBanner(pending ? sourceBanner(pending) : "");
|
||||
}, [access, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]);
|
||||
}, [access, graphEnabled, graphKey, personal, selectedSourceIds, sources, source, styleName, syncGotoFromMap, updateHud]);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
const [sourceList, syncStatus] = await Promise.all([
|
||||
@@ -351,6 +323,39 @@ export function App() {
|
||||
void loadStyle().catch((err: unknown) => setBanner(err instanceof Error ? err.message : "Ошибка стиля"));
|
||||
}, [loadStyle]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!personal || !graphEnabled) {
|
||||
setGraphMeta(null);
|
||||
return;
|
||||
}
|
||||
const first = graphSources[0];
|
||||
if (!first) {
|
||||
setGraphMeta(null);
|
||||
if (selectedSourceIds.length > 0) {
|
||||
setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract.");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
void fetchJson<GraphMeta>(graphMetaUrl(access, first.id))
|
||||
.then((meta) => {
|
||||
if (!cancelled) {
|
||||
setGraphMeta(meta);
|
||||
setGraphError("");
|
||||
}
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (!cancelled) {
|
||||
setGraphMeta(null);
|
||||
setGraphError(err instanceof Error ? err.message : "Не удалось прочитать метаданные графа");
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [access, graphEnabled, graphKey, personal, selectedSourceIds.length]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
mapRef.current?.remove();
|
||||
@@ -418,64 +423,6 @@ export function App() {
|
||||
}
|
||||
};
|
||||
|
||||
const clearGraph = () => {
|
||||
graphEnabledRef.current = false;
|
||||
setGraphEnabled(false);
|
||||
clearGraphLayers(mapRef.current);
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
};
|
||||
|
||||
const loadGraph = async () => {
|
||||
if (!personal) {
|
||||
setGraphError("Нужны slug и токен.");
|
||||
return;
|
||||
}
|
||||
const map = mapRef.current;
|
||||
if (!map) {
|
||||
setGraphError("Карта ещё не готова.");
|
||||
return;
|
||||
}
|
||||
if (graphSources.length === 0) {
|
||||
setGraphError("У выбранных округов граф ещё не собран. Синхронизируй extract.");
|
||||
return;
|
||||
}
|
||||
|
||||
setGraphLoading(true);
|
||||
setGraphError("");
|
||||
try {
|
||||
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);
|
||||
setGraphError(err instanceof Error ? err.message : "Не удалось подключить тайлы графа");
|
||||
} finally {
|
||||
setGraphLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const mixedStatus = selectedSources.some((item) => item.status === "Failed")
|
||||
? "Failed"
|
||||
: selectedSources.every((item) => item.status === "Ready")
|
||||
@@ -541,7 +488,8 @@ export function App() {
|
||||
const next = { slug: slugDraft.trim(), token: tokenDraft.trim() };
|
||||
persistAccess(next);
|
||||
styleKeyRef.current = null;
|
||||
clearGraph();
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
setAccess(next);
|
||||
}}
|
||||
>
|
||||
@@ -556,7 +504,8 @@ export function App() {
|
||||
setTokenDraft("");
|
||||
persistAccess({ slug: "", token: "" });
|
||||
styleKeyRef.current = null;
|
||||
clearGraph();
|
||||
setGraphMeta(null);
|
||||
setGraphError("");
|
||||
setAccess({ slug: "", token: "" });
|
||||
}}
|
||||
>
|
||||
@@ -617,27 +566,24 @@ export function App() {
|
||||
<summary>Граф дорог</summary>
|
||||
<div className="graph-panel">
|
||||
<p className="graph-panel__hint">
|
||||
Векторные тайлы <code>graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code>
|
||||
Тайлы <code>/graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code> вшиты в стиль как vector source,
|
||||
слой <code>roads</code>, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}
|
||||
{graphSources.length > 0
|
||||
? ` — ${graphSources.map((item) => `«${item.name}»`).join(", ")}`
|
||||
: graphSource
|
||||
? ` («${graphSource.name}»)`
|
||||
: ""}
|
||||
. Слой <code>roads</code>, z {GRAPH_MIN_ZOOM}–{GRAPH_MAX_ZOOM}. Оранжевые линии поверх OSM.
|
||||
. Оранжевые линии поверх OSM.
|
||||
</p>
|
||||
<div className="graph-panel__actions">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--accent"
|
||||
disabled={graphLoading || !personal || graphEnabled}
|
||||
onClick={() => void loadGraph()}
|
||||
>
|
||||
{graphLoading ? "Подключение…" : "Показать граф"}
|
||||
</button>
|
||||
<button type="button" className="btn" disabled={!graphEnabled} onClick={clearGraph}>
|
||||
Снять слой
|
||||
</button>
|
||||
</div>
|
||||
<label className="graph-panel__toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={graphEnabled}
|
||||
disabled={!personal}
|
||||
onChange={(e) => setGraphEnabled(e.target.checked)}
|
||||
/>
|
||||
Показывать тайлы графа
|
||||
</label>
|
||||
{graphError ? <p className="error">{graphError}</p> : null}
|
||||
{graphMeta ? (
|
||||
<dl>
|
||||
|
||||
+22
-3
@@ -76,16 +76,35 @@ export function graphTilesUrl(access: Access, sourceId: string): string {
|
||||
);
|
||||
}
|
||||
|
||||
const TILE_PLACEHOLDERS: Record<string, string> = {
|
||||
"{z}": "__TS_Z__",
|
||||
"{x}": "__TS_X__",
|
||||
"{y}": "__TS_Y__"
|
||||
};
|
||||
|
||||
export function rewriteServiceUrl(url: string, access: Access): string {
|
||||
const resolved = new URL(url, `${API_ORIGIN}/`);
|
||||
let masked = url;
|
||||
for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) {
|
||||
masked = masked.replaceAll(token, sentinel);
|
||||
}
|
||||
|
||||
const resolved = new URL(masked, `${API_ORIGIN}/`);
|
||||
const isService = resolved.pathname.startsWith("/u/") || resolved.pathname.startsWith("/api/");
|
||||
if (!isService) {
|
||||
return resolved.href;
|
||||
return restoreTilePlaceholders(resolved.href);
|
||||
}
|
||||
|
||||
if (isPersonal(access) && resolved.pathname.startsWith("/u/") && !resolved.searchParams.has("token")) {
|
||||
resolved.searchParams.set("token", access.token);
|
||||
}
|
||||
|
||||
return `${API_ORIGIN}${resolved.pathname}${resolved.search}`;
|
||||
return restoreTilePlaceholders(`${API_ORIGIN}${resolved.pathname}${resolved.search}`);
|
||||
}
|
||||
|
||||
function restoreTilePlaceholders(url: string): string {
|
||||
let restored = url;
|
||||
for (const [token, sentinel] of Object.entries(TILE_PLACEHOLDERS)) {
|
||||
restored = restored.replaceAll(sentinel, token);
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
+12
-3
@@ -364,10 +364,19 @@ button:disabled { opacity: 0.55; cursor: wait; }
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.graph-panel__actions {
|
||||
.graph-panel__toggle {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
gap: 0.55rem;
|
||||
font-size: 0.86rem;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.graph-panel__toggle input {
|
||||
width: 1.05rem;
|
||||
height: 1.05rem;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.graph-panel__bbox {
|
||||
|
||||
@@ -272,11 +272,11 @@ export function GraphPage() {
|
||||
>
|
||||
<ul className="graph-page__list">
|
||||
<li>Добавляйте source после load / idle — иначе MapLibre отбросит слой при смене стиля.</li>
|
||||
<li>С z12 сервер отдаёт все highway, включая residential/service (до 40k рёбер на тайл).</li>
|
||||
<li>
|
||||
z 6–8: motorway/trunk; z 9–10: + primary; z 11–12: + secondary/tertiary; z 13+: все классы, до 8000 рёбер на
|
||||
тайл.
|
||||
После sync геометрия — полилиния OSM между перекрёстками. Старый sqlite без колонки geom рисует хорды —
|
||||
пересоберите граф.
|
||||
</li>
|
||||
<li>Геометрия — прямая между вершинами графа, не исходная полилиния OSM.</li>
|
||||
</ul>
|
||||
<CopyField code label="MapLibre: слой поверх стиля" value={urls.mapLibre} />
|
||||
<CopyField code label="HTML: карта + граф" value={urls.html} />
|
||||
|
||||
@@ -168,8 +168,8 @@ const map = new maplibregl.Map({
|
||||
Поля: <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°.
|
||||
На мелком зуме только крупные дороги (z≤8 motorway/trunk, затем primary, secondary). С z12 — все улицы,
|
||||
включая residential. JSON <code>/nodes</code> и <code>/edges</code> — точечная выборка, сторона bbox ≤ 2°.
|
||||
</li>
|
||||
<li>
|
||||
Нет файла графа → 404. Дождитесь sync или <code>POST /api/v1/sync/{"{id}"}</code> при{" "}
|
||||
@@ -190,7 +190,8 @@ const map = new maplibregl.Map({
|
||||
<h2 className="guides__h">Граф дорог</h2>
|
||||
<p className="guides__lead">
|
||||
Тайлы графа — как OSM: <code>/graph/{"{source}"}/{"{z}"}/{"{x}"}/{"{y}"}.pbf</code>, слой <code>roads</code>.
|
||||
Ниже примеры уже с вашим slug, округом и токеном. Геометрия ребра — прямая между вершинами, не полилиния OSM.
|
||||
Ниже примеры уже с вашим slug, округом и токеном. С z12 — все классы улиц. После пересборки графа
|
||||
геометрия — полилиния OSM между перекрёстками.
|
||||
</p>
|
||||
<CopyBlock label="Тайлы MVT" value={graph.tiles} />
|
||||
<CopyBlock label="TileJSON" value={graph.tilejson} />
|
||||
|
||||
Reference in New Issue
Block a user