/** * คำนวณระยะทางระหว่างตำแหน่งอุปกรณ์กับโรงหนัง * - ระยะทางตามถนน: OSRM table service (คำขอเดียวได้ทุกโรง) * - ถ้าเรียกไม่สำเร็จ: ระยะเส้นตรง × factor แล้วติดป้าย "≈" ให้ผู้ใช้รู้ว่าเป็นค่าประมาณ */ export type Coordinates = { latitude: number; longitude: number; }; export type DistanceSource = "road" | "straight"; export type DistanceResult = { distance_km: number; source: DistanceSource; }; const OSRM_TABLE_ENDPOINT = "https://router.project-osrm.org/table/v1/driving"; /** ตัวคูณชดเชยเส้นทางจริงในเมือง (ถนนอ้อมมุมถนน) ใช้เฉพาะตอนคำนวณแบบเส้นตรง */ const DETOUR_FACTOR = 1.35; const EARTH_RADIUS_KM = 6371; const OSRM_TIMEOUT_MS = 8000; function toRadians(degrees: number): number { return (degrees * Math.PI) / 180; } /** ระยะทางเส้นตรงบนผิวโลก */ export function haversineKm(from: Coordinates, to: Coordinates): number { const deltaLat = toRadians(to.latitude - from.latitude); const deltaLon = toRadians(to.longitude - from.longitude); const a = Math.sin(deltaLat / 2) ** 2 + Math.cos(toRadians(from.latitude)) * Math.cos(toRadians(to.latitude)) * Math.sin(deltaLon / 2) ** 2; return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(a)); } export function straightLineDistance( from: Coordinates, to: Coordinates, ): DistanceResult { return { distance_km: haversineKm(from, to) * DETOUR_FACTOR, source: "straight", }; } /** อ่านเมทริกซ์ระยะทาง (เมตร) จาก OSRM — แถวแรกคือต้นทาง (ตำแหน่งอุปกรณ์) */ export function parseOsrmTable(meters: unknown): (number | null)[] { if (!Array.isArray(meters) || !Array.isArray(meters[0])) return []; const firstRow = meters[0] as unknown[]; return firstRow.slice(1).map((value) => typeof value === "number" && Number.isFinite(value) ? value / 1000 : null, ); } function buildTableUrl(origin: Coordinates, destinations: Coordinates[]): string { const points = [origin, ...destinations] .map((point) => `${point.longitude},${point.latitude}`) .join(";"); return `${OSRM_TABLE_ENDPOINT}/${points}?annotations=distance`; } /** * ระยะทางตามถนนจากตำแหน่งอุปกรณ์ไปยังทุกจุดหมายในคำขอเดียว * ลำดับผลลัพธ์ตรงกับ `destinations`; จุดที่หาเส้นทางไม่ได้จะคืน null */ export async function fetchRoadDistances( origin: Coordinates, destinations: Coordinates[], ): Promise<(DistanceResult | null)[]> { if (destinations.length === 0) return []; const response = await fetch(buildTableUrl(origin, destinations), { signal: AbortSignal.timeout(OSRM_TIMEOUT_MS), }); if (!response.ok) { throw new Error(`OSRM ตอบกลับ ${response.status}`); } const payload = (await response.json()) as { code?: string; distances?: unknown; }; if (payload.code !== "Ok") { throw new Error(`OSRM code: ${payload.code ?? "unknown"}`); } const kilometres = parseOsrmTable(payload.distances); return destinations.map((_, index) => { const distance = kilometres[index]; return distance === null || distance === undefined ? null : { distance_km: distance, source: "road" as const }; }); } /** ระยะทางที่แสดงบนการ์ด: 1 ตำแหน่งทศนิยม และเติม "≈" เมื่อเป็นค่าประมาณ */ export function formatDistance( result: DistanceResult | null | undefined, fallback: string, ): string { if (!result) return fallback; const prefix = result.source === "straight" ? "≈ " : ""; return `${prefix}${result.distance_km.toFixed(1)} km.`; } /** เรียงจากใกล้สุดไปไกลสุด — โรงที่ยังไม่ทราบระยะทางไปไว้ท้ายเสมอ */ export function sortByDistance( items: T[], distances: Record, ): T[] { return [...items].sort((first, second) => { const a = distances[first.slug]?.distance_km; const b = distances[second.slug]?.distance_km; if (a === undefined && b === undefined) return 0; if (a === undefined) return 1; if (b === undefined) return -1; return a - b; }); }