const METERS_PER_DEGREE_LAT = 110_540; const METERS_PER_DEGREE_LON_AT_EQUATOR = 111_320; export interface Outline { id: string; polygons: number[][][][]; } export function containsPoint(polygons: number[][][][], lon: number, lat: number): boolean { return polygons.some( ([outer, ...holes]) => !!outer && insideRing(outer, lon, lat) && !holes.some((hole) => insideRing(hole, lon, lat)), ); } export function distanceToOutline(polygons: number[][][][], lon: number, lat: number): number { if (containsPoint(polygons, lon, lat)) { return 0; } const kx = METERS_PER_DEGREE_LON_AT_EQUATOR * Math.cos((lat * Math.PI) / 180); const ky = METERS_PER_DEGREE_LAT; let best = Infinity; for (const polygon of polygons) { for (const ring of polygon) { for (let i = 1; i < ring.length; i++) { const ax = (ring[i - 1][0] - lon) * kx; const ay = (ring[i - 1][1] - lat) * ky; const bx = (ring[i][0] - lon) * kx; const by = (ring[i][1] - lat) * ky; best = Math.min(best, distanceToSegment(ax, ay, bx, by)); } } } return best; } export function assignToOutlines( outlines: Outline[], items: T[], position: (item: T) => [number, number] | null, maxDistanceMeters: number, ): Map { const result = new Map(); for (const item of items) { const point = position(item); if (!point) { continue; } const [lon, lat] = point; let bestId: string | null = null; let bestDistance = maxDistanceMeters; for (const outline of outlines) { const distance = distanceToOutline(outline.polygons, lon, lat); if (distance <= bestDistance) { bestId = outline.id; bestDistance = distance; if (distance === 0) { break; } } } if (bestId !== null) { result.set(bestId, [...(result.get(bestId) ?? []), item]); } } return result; } function insideRing(ring: number[][], x: number, y: number): boolean { let inside = false; for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { const [xi, yi] = ring[i]; const [xj, yj] = ring[j]; if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) { inside = !inside; } } return inside; } function distanceToSegment(ax: number, ay: number, bx: number, by: number): number { const dx = bx - ax; const dy = by - ay; const lengthSquared = dx * dx + dy * dy; const t = lengthSquared === 0 ? 0 : Math.max(0, Math.min(1, -(ax * dx + ay * dy) / lengthSquared)); return Math.hypot(ax + t * dx, ay + t * dy); }