dika/src/route.js

27 lines
1.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Пеший маршрут от пользователя до заведений (DIK-45).
// Источник — OSRM (профиль «пешком»), адрес меняется переменной ROUTE_URL. Один запрос на весь список.
// Не вышло (сеть, тайм-аут, нет пути) — вызывающий код считает по прямой и пишет «примерно».
export const WALK_M_PER_MIN = 80; // ~4,8 км/ч — для расчёта по прямой
const DEFAULT_URL = "https://routing.openstreetmap.de/routed-foot";
export const approxWalk = (straightM) => ({ m: straightM, min: Math.max(1, Math.round(straightM / WALK_M_PER_MIN)), approx: true });
// → Map<id, {m, min, approx:false}>; заведения без маршрута в Map нет
export async function walkRoutes(lat, lng, venues, { fetchFn = fetch, baseUrl = process.env.ROUTE_URL || DEFAULT_URL, timeoutMs = 4000 } = {}) {
const out = new Map();
if (!venues.length || baseUrl === "off") return out;
try {
const pts = [[lng, lat], ...venues.map((v) => [v.lng, v.lat])].map((p) => p.join(",")).join(";");
const r = await fetchFn(`${baseUrl}/table/v1/foot/${pts}?sources=0&annotations=distance,duration`, { signal: AbortSignal.timeout(timeoutMs) });
if (!r.ok) return out;
const j = await r.json();
if (j.code !== "Ok") return out;
const dist = j.distances?.[0], dur = j.durations?.[0];
venues.forEach((v, i) => {
const m = dist?.[i + 1], s = dur?.[i + 1];
if (Number.isFinite(m) && Number.isFinite(s)) out.set(v.id, { m: Math.round(m), min: Math.max(1, Math.round(s / 60)), approx: false });
});
} catch { /* маршрут не посчитан — будет «примерно» */ }
return out;
}