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
+51 -16
View File
@@ -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 ? (
+20
View File
@@ -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));
+142
View File
@@ -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}"`
};
}
+51 -39
View File
@@ -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} />
+18
View File
@@ -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);