fix(graph): tiles

This commit is contained in:
vl.arkhangelskii
2026-09-21 13:48:00 +03:00
parent 236c0bc754
commit 1d71e440f9
22 changed files with 1153 additions and 265 deletions
+132 -189
View File
@@ -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>
+2 -8
View File
@@ -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)}`
);
}