mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
feat(roadtrip): find fuel, rest areas and sights along the drive
The road trip mode could show the route but not what sits beside it, which is half of what planning a drive is about (#1797). The right column becomes a corridor search: pick what you need, pick how far off the route you will go for it, and the day's drive is searched box by box. The boxes come from the route itself rather than the viewport, so the answer is "on the way", not "on screen"; each hit reports how far off the route it lies and how far into the drive it comes, and adding one opens the normal place form so it lands on the day like any other stop. Overpass is asked in plain bounding boxes rather than with a polyline filter, because that is what the existing /api/maps/pois route accepts and what the mirrors can answer; the geometry work is pure and tested. Long routes stop at ten boxes and say so instead of quietly searching half the drive. Fuel, charging, rest areas and campsites join the server's POI categories, so the explore pill and the MCP search_pois tool gain them too. A car booking's stops now also reach the PDF, which printed pick-up and return with everything in between missing.
This commit is contained in:
@@ -353,6 +353,13 @@ export async function downloadTripPDF({ trip, days, places, assignments = {}, ca
|
||||
subtitle = [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : '', meta.seat ? `Seat ${meta.seat}` : '', route].filter(Boolean).join(' · ')
|
||||
}
|
||||
}
|
||||
else if (r.type === 'car') {
|
||||
// A rental with stops is a drive, and the printout is what people take
|
||||
// into the car (#1797). Without this the route reads as pick-up and return
|
||||
// with everything in between missing.
|
||||
const stops = (r.endpoints || []).slice().sort((a, b) => (a.sequence ?? 0) - (b.sequence ?? 0)).map(e => e.name)
|
||||
subtitle = stops.length >= 2 ? stops.join(' → ') : ''
|
||||
}
|
||||
else if (r.type === 'restaurant') subtitle = [meta.party_size ? `${meta.party_size} guests` : ''].filter(Boolean).join(' · ')
|
||||
else if (r.type === 'event') subtitle = [meta.venue].filter(Boolean).join(' · ')
|
||||
else if (r.type === 'tour') subtitle = [meta.operator].filter(Boolean).join(' · ')
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import { Fuel, Zap, ParkingSquare, Tent, Utensils, Camera, Search, Plus, RotateCw, AlertTriangle, type LucideIcon } from 'lucide-react'
|
||||
import { useTranslation } from '../../i18n/TranslationContext'
|
||||
import { useSettingsStore } from '../../store/settingsStore'
|
||||
import { formatDistance } from '../../utils/units'
|
||||
import CustomSelect from '../shared/CustomSelect'
|
||||
import { useCorridorPois, type CorridorPoi } from './useCorridorPois'
|
||||
import type { LatLng } from './corridor'
|
||||
import type { RoadtripRoutes } from './useRoadtripRoutes'
|
||||
|
||||
interface RoadtripCorridorPanelProps {
|
||||
routes: RoadtripRoutes
|
||||
/** Opens the place form prefilled from a POI, optionally on a day. */
|
||||
onAddPoi?: (
|
||||
poi: { lat: number; lng: number; name: string; address: string | null; website: string | null; phone: string | null; osm_id: string },
|
||||
dayId?: number | null,
|
||||
) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* What a drive needs, rather than what a city visit does. Deliberately a short list:
|
||||
* every extra category is another round of requests against a shared Overpass mirror.
|
||||
*/
|
||||
const CORRIDOR_CATEGORIES: { key: string; labelKey: string; Icon: LucideIcon }[] = [
|
||||
{ key: 'fuel', labelKey: 'roadtrip.poi.fuel', Icon: Fuel },
|
||||
{ key: 'charging', labelKey: 'roadtrip.poi.charging', Icon: Zap },
|
||||
{ key: 'rest_area', labelKey: 'roadtrip.poi.rest', Icon: ParkingSquare },
|
||||
{ key: 'campsite', labelKey: 'roadtrip.poi.campsite', Icon: Tent },
|
||||
{ key: 'restaurant', labelKey: 'roadtrip.poi.food', Icon: Utensils },
|
||||
{ key: 'sights', labelKey: 'roadtrip.poi.sights', Icon: Camera },
|
||||
]
|
||||
|
||||
const CATEGORY_ICON: Record<string, LucideIcon> = Object.fromEntries(
|
||||
CORRIDOR_CATEGORIES.map(c => [c.key, c.Icon]),
|
||||
)
|
||||
|
||||
const WIDTHS_KM = [2, 5, 10]
|
||||
|
||||
function ResultRow({ poi, onAdd }: { poi: CorridorPoi; onAdd?: () => void }): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const Icon = CATEGORY_ICON[poi.category] ?? Camera
|
||||
return (
|
||||
<div className="flex items-center gap-2.5 px-2 py-2 rounded-xl hover:bg-surface-hover">
|
||||
<Icon size={15} className="shrink-0 text-content-faint" aria-hidden />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-body text-content truncate">{poi.name}</div>
|
||||
<div className="text-caption text-content-faint tabular-nums">
|
||||
{t('roadtrip.poi.offRoute', { distance: formatDistance(poi.offRouteKm, distanceUnit) })}
|
||||
<span className="mx-1">·</span>
|
||||
{/* A candidate beside the first stop projects to the very start of the line;
|
||||
printing that as "after 0 m" reads like a bug rather than "right here". */}
|
||||
{poi.alongKm < 0.5
|
||||
? t('roadtrip.poi.atStart')
|
||||
: t('roadtrip.poi.alongRoute', { distance: formatDistance(poi.alongKm, distanceUnit) })}
|
||||
</div>
|
||||
</div>
|
||||
{onAdd ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onAdd}
|
||||
className="shrink-0 flex items-center gap-1 rounded-lg px-2 py-1 text-caption text-content-secondary hover:text-content hover:bg-surface-selected"
|
||||
>
|
||||
<Plus size={12} aria-hidden />
|
||||
{t('roadtrip.poi.add')}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* "What is on the way" — the right column while road trip mode is on.
|
||||
*
|
||||
* Searching is a button, not a side effect of panning: one run is several Overpass
|
||||
* requests and the mirrors are shared infrastructure. The scope is one day's drive by
|
||||
* default, which keeps a run to a handful of boxes and makes "add this" unambiguous —
|
||||
* the stop lands on the day whose route it was found along.
|
||||
*/
|
||||
export default function RoadtripCorridorPanel({ routes, onAddPoi }: RoadtripCorridorPanelProps): React.ReactElement {
|
||||
const { t } = useTranslation()
|
||||
const distanceUnit = useSettingsStore(s => s.settings.distance_unit)
|
||||
const [dayId, setDayId] = useState<string>(() => String(routes.days[0]?.dayId ?? ''))
|
||||
const [active, setActive] = useState<string[]>(['fuel'])
|
||||
const [widthKm, setWidthKm] = useState<number>(5)
|
||||
|
||||
const day = routes.days.find(d => String(d.dayId) === dayId) ?? routes.days[0]
|
||||
const line = useMemo<LatLng[]>(() => {
|
||||
if (!day) return []
|
||||
// The stops themselves are enough of a spine: the corridor is kilometres wide, and
|
||||
// the routed geometry per leg is not kept once its numbers are read.
|
||||
return day.stops.map(s => ({ lat: s.lat, lng: s.lng }))
|
||||
}, [day])
|
||||
|
||||
const search = useCorridorPois(line, active, widthKm)
|
||||
|
||||
const dayOptions = routes.days.map(d => ({
|
||||
value: String(d.dayId),
|
||||
label: t('roadtrip.day', { number: d.dayNumber }),
|
||||
}))
|
||||
|
||||
const toggle = (key: string): void =>
|
||||
setActive(prev => (prev.includes(key) ? prev.filter(k => k !== key) : [...prev, key]))
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="px-3 pt-3 pb-2 flex flex-col gap-2.5">
|
||||
<h2 className="text-subtitle font-semibold text-content">{t('roadtrip.poi.title')}</h2>
|
||||
|
||||
{dayOptions.length > 1 ? (
|
||||
<CustomSelect value={dayId} onChange={value => setDayId(String(value))} options={dayOptions} size="sm" />
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{CORRIDOR_CATEGORIES.map(({ key, labelKey, Icon }) => {
|
||||
const on = active.includes(key)
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
onClick={() => toggle(key)}
|
||||
className={`flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-caption transition-colors ${
|
||||
on
|
||||
? 'bg-accent text-accent-text border-transparent'
|
||||
: 'bg-surface-card text-content-secondary border-edge hover:border-edge-secondary'
|
||||
}`}
|
||||
>
|
||||
<Icon size={12} aria-hidden />
|
||||
{t(labelKey)}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-caption text-content-faint">{t('roadtrip.poi.within')}</span>
|
||||
<div className="flex gap-1 p-0.5 rounded-lg bg-surface-tertiary border border-edge-faint">
|
||||
{WIDTHS_KM.map(km => (
|
||||
<button
|
||||
key={km}
|
||||
type="button"
|
||||
aria-pressed={widthKm === km}
|
||||
onClick={() => setWidthKm(km)}
|
||||
className={`rounded-md px-2 py-0.5 text-caption tabular-nums transition-colors ${
|
||||
widthKm === km ? 'bg-surface-card text-content' : 'text-content-muted hover:text-content'
|
||||
}`}
|
||||
>
|
||||
{formatDistance(km, distanceUnit)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={search.search}
|
||||
disabled={search.loading || active.length === 0 || line.length < 2}
|
||||
className="flex items-center justify-center gap-1.5 rounded-lg bg-inverse text-inverse-text px-3 py-2 text-body font-medium disabled:opacity-50"
|
||||
>
|
||||
{search.loading ? <RotateCw size={14} className="animate-spin" aria-hidden /> : <Search size={14} aria-hidden />}
|
||||
{search.loading
|
||||
? t('roadtrip.poi.searching', { done: search.progress.done, total: search.progress.total })
|
||||
: t('roadtrip.poi.search')}
|
||||
</button>
|
||||
|
||||
{search.capped ? (
|
||||
<p className="flex items-start gap-1.5 text-caption text-warning">
|
||||
<AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden />
|
||||
{t('roadtrip.poi.capped')}
|
||||
</p>
|
||||
) : null}
|
||||
{search.error ? (
|
||||
<p className="flex items-start gap-1.5 text-caption text-danger">
|
||||
<AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden />
|
||||
{t('roadtrip.poi.failed')}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-1.5 pb-3">
|
||||
{search.results.length === 0 && !search.loading ? (
|
||||
<p className="px-3 py-6 text-caption text-content-muted text-center">{t('roadtrip.poi.empty')}</p>
|
||||
) : (
|
||||
search.results.map(poi => (
|
||||
<ResultRow
|
||||
key={poi.osm_id}
|
||||
poi={poi}
|
||||
onAdd={onAddPoi ? () => onAddPoi(poi, day?.dayId ?? null) : undefined}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
corridorTiles,
|
||||
distanceToSegmentKm,
|
||||
haversineKm,
|
||||
projectOntoRoute,
|
||||
simplifyLine,
|
||||
type LatLng,
|
||||
} from './corridor'
|
||||
|
||||
const BERLIN: LatLng = { lat: 52.52, lng: 13.405 }
|
||||
const DRESDEN: LatLng = { lat: 51.05, lng: 13.74 }
|
||||
const PRAGUE: LatLng = { lat: 50.088, lng: 14.42 }
|
||||
|
||||
describe('haversineKm', () => {
|
||||
it('measures a known distance', () => {
|
||||
// Berlin → Dresden is about 165 km as the crow flies.
|
||||
expect(haversineKm(BERLIN, DRESDEN)).toBeGreaterThan(160)
|
||||
expect(haversineKm(BERLIN, DRESDEN)).toBeLessThan(170)
|
||||
})
|
||||
|
||||
it('is zero for the same point', () => {
|
||||
expect(haversineKm(BERLIN, BERLIN)).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('distanceToSegmentKm', () => {
|
||||
const a: LatLng = { lat: 52, lng: 13 }
|
||||
const b: LatLng = { lat: 52, lng: 14 }
|
||||
|
||||
it('measures perpendicular distance to the line', () => {
|
||||
const p: LatLng = { lat: 52.09, lng: 13.5 }
|
||||
// 0.09° of latitude is about 10 km, whatever the longitude does.
|
||||
expect(distanceToSegmentKm(p, a, b)).toBeGreaterThan(9)
|
||||
expect(distanceToSegmentKm(p, a, b)).toBeLessThan(11)
|
||||
})
|
||||
|
||||
it('measures to the end, not to the infinite line, for a point beyond it', () => {
|
||||
const beyond: LatLng = { lat: 52, lng: 16 }
|
||||
const d = distanceToSegmentKm(beyond, a, b)
|
||||
// Two degrees of longitude past the end at 52° north — roughly 137 km.
|
||||
expect(d).toBeGreaterThan(120)
|
||||
expect(d).toBeLessThan(150)
|
||||
})
|
||||
|
||||
it('falls back to point distance for a zero-length segment', () => {
|
||||
expect(distanceToSegmentKm(DRESDEN, a, a)).toBeCloseTo(haversineKm(DRESDEN, a), 5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('projectOntoRoute', () => {
|
||||
const line = [BERLIN, DRESDEN, PRAGUE]
|
||||
|
||||
it('reports how far off the route a point is', () => {
|
||||
const onRoute = projectOntoRoute({ lat: 51.8, lng: 13.5 }, line)
|
||||
expect(onRoute!.offRouteKm).toBeLessThan(15)
|
||||
const wayOff = projectOntoRoute({ lat: 53.55, lng: 10.0 }, line)
|
||||
expect(wayOff!.offRouteKm).toBeGreaterThan(150)
|
||||
})
|
||||
|
||||
it('orders points by how far into the drive they come', () => {
|
||||
const early = projectOntoRoute({ lat: 52.3, lng: 13.45 }, line)!
|
||||
const late = projectOntoRoute({ lat: 50.4, lng: 14.2 }, line)!
|
||||
expect(early.alongKm).toBeLessThan(late.alongKm)
|
||||
})
|
||||
|
||||
it('tells two points on the same long straight apart', () => {
|
||||
// The petrol stations along one motorway segment must not all report the same
|
||||
// position in the drive, which is what taking the segment midpoint produced.
|
||||
const straight = [{ lat: 52, lng: 13 }, { lat: 52, lng: 15 }]
|
||||
const early = projectOntoRoute({ lat: 52.01, lng: 13.3 }, straight)!
|
||||
const late = projectOntoRoute({ lat: 52.01, lng: 14.7 }, straight)!
|
||||
expect(late.alongKm - early.alongKm).toBeGreaterThan(80)
|
||||
})
|
||||
|
||||
it('returns nothing for a line that is not one', () => {
|
||||
expect(projectOntoRoute(BERLIN, [])).toBeNull()
|
||||
expect(projectOntoRoute(BERLIN, [BERLIN])).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('corridorTiles', () => {
|
||||
it('covers a short route with a single box', () => {
|
||||
const tiles = corridorTiles([BERLIN, { lat: 52.4, lng: 13.5 }], 5)
|
||||
expect(tiles).toHaveLength(1)
|
||||
expect(tiles[0].south).toBeLessThan(52.4)
|
||||
expect(tiles[0].north).toBeGreaterThan(52.52)
|
||||
})
|
||||
|
||||
it('splits a long route into boxes the server will not clamp', () => {
|
||||
const tiles = corridorTiles([BERLIN, DRESDEN, PRAGUE], 10)
|
||||
expect(tiles.length).toBeGreaterThan(1)
|
||||
for (const t of tiles) {
|
||||
expect(t.north - t.south).toBeLessThanOrEqual(0.45)
|
||||
expect(t.east - t.west).toBeLessThanOrEqual(0.45)
|
||||
}
|
||||
})
|
||||
|
||||
it('pads longitude more the further north it goes', () => {
|
||||
const south = corridorTiles([{ lat: 0, lng: 0 }], 10)[0]
|
||||
const north = corridorTiles([{ lat: 60, lng: 0 }], 10)[0]
|
||||
expect(north.east - north.west).toBeGreaterThan(south.east - south.west)
|
||||
})
|
||||
|
||||
it('has nothing to cover for an empty route', () => {
|
||||
expect(corridorTiles([], 10)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('simplifyLine', () => {
|
||||
it('keeps the ends and drops what sits on the line between them', () => {
|
||||
const straight = [
|
||||
{ lat: 52, lng: 13 },
|
||||
{ lat: 52, lng: 13.5 },
|
||||
{ lat: 52, lng: 14 },
|
||||
]
|
||||
expect(simplifyLine(straight, 1)).toEqual([straight[0], straight[2]])
|
||||
})
|
||||
|
||||
it('keeps a point that actually bends the route', () => {
|
||||
const bent = [
|
||||
{ lat: 52, lng: 13 },
|
||||
{ lat: 52.5, lng: 13.5 },
|
||||
{ lat: 52, lng: 14 },
|
||||
]
|
||||
expect(simplifyLine(bent, 1)).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('leaves a two-point line alone', () => {
|
||||
expect(simplifyLine([BERLIN, DRESDEN], 5)).toEqual([BERLIN, DRESDEN])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
/**
|
||||
* Corridor geometry — "what lies along this drive", without asking Overpass to think
|
||||
* about a polyline.
|
||||
*
|
||||
* The naive form (`around:` with a hundred coordinates) is what every POI provider warns
|
||||
* about and times out on. OsmAnd solves it the other way round and this follows it: ask
|
||||
* for plain bounding boxes that cover the route, then measure each candidate's
|
||||
* perpendicular distance to the line and throw away what is too far. The boxes are what
|
||||
* the existing /api/maps/pois route already accepts, so no new server surface is needed.
|
||||
*
|
||||
* Everything here is pure: no React, no network, no store.
|
||||
*/
|
||||
|
||||
export interface LatLng {
|
||||
lat: number
|
||||
lng: number
|
||||
}
|
||||
|
||||
export interface Bbox {
|
||||
south: number
|
||||
west: number
|
||||
north: number
|
||||
east: number
|
||||
}
|
||||
|
||||
const EARTH_RADIUS_KM = 6371
|
||||
const KM_PER_DEG_LAT = 111.32
|
||||
|
||||
const toRad = (deg: number): number => (deg * Math.PI) / 180
|
||||
|
||||
/** Great-circle distance in kilometres. */
|
||||
export function haversineKm(a: LatLng, b: LatLng): number {
|
||||
const dLat = toRad(b.lat - a.lat)
|
||||
const dLng = toRad(b.lng - a.lng)
|
||||
const lat1 = toRad(a.lat)
|
||||
const lat2 = toRad(b.lat)
|
||||
const h =
|
||||
Math.sin(dLat / 2) ** 2 + Math.sin(dLng / 2) ** 2 * Math.cos(lat1) * Math.cos(lat2)
|
||||
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(h)))
|
||||
}
|
||||
|
||||
/**
|
||||
* Perpendicular distance from a point to a line segment, in kilometres.
|
||||
*
|
||||
* Works in a local equirectangular projection around the segment: longitudes shrink by
|
||||
* cos(lat), which is the whole reason a uniform degree padding is wrong at 60° north.
|
||||
* Over the few kilometres a corridor spans, the error against a proper geodesic is far
|
||||
* below the width the user picked.
|
||||
*/
|
||||
export function distanceToSegmentKm(p: LatLng, a: LatLng, b: LatLng): number {
|
||||
return projectOnSegment(p, a, b).distanceKm
|
||||
}
|
||||
|
||||
/**
|
||||
* Perpendicular distance to a segment plus where along it the foot of that perpendicular
|
||||
* falls (0 at `a`, 1 at `b`). The second number is what places a candidate correctly in
|
||||
* the drive — taking the segment's midpoint instead makes every petrol station on a long
|
||||
* straight report the same position.
|
||||
*/
|
||||
export function projectOnSegment(p: LatLng, a: LatLng, b: LatLng): { distanceKm: number; t: number } {
|
||||
const latScale = KM_PER_DEG_LAT
|
||||
const lngScale = KM_PER_DEG_LAT * Math.cos(toRad((a.lat + b.lat) / 2))
|
||||
const ax = a.lng * lngScale
|
||||
const ay = a.lat * latScale
|
||||
const bx = b.lng * lngScale
|
||||
const by = b.lat * latScale
|
||||
const px = p.lng * lngScale
|
||||
const py = p.lat * latScale
|
||||
const dx = bx - ax
|
||||
const dy = by - ay
|
||||
const lenSq = dx * dx + dy * dy
|
||||
if (lenSq === 0) return { distanceKm: haversineKm(p, a), t: 0 }
|
||||
// Clamped so a point beside the segment's end measures to the end, not to the
|
||||
// infinite line — otherwise a stop 200 km past the destination looks "on the way".
|
||||
const t = Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / lenSq))
|
||||
const cx = ax + t * dx
|
||||
const cy = ay + t * dy
|
||||
return { distanceKm: Math.hypot(px - cx, py - cy), t }
|
||||
}
|
||||
|
||||
export interface CorridorHit {
|
||||
/** Kilometres from the route line at its closest point. */
|
||||
offRouteKm: number
|
||||
/** Kilometres travelled along the route before reaching that closest point. */
|
||||
alongKm: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a point sits relative to the route: how far off it is, and how far into the
|
||||
* drive it comes. The second number is what puts "lunch" before "the hotel" in a list
|
||||
* instead of sorting by name.
|
||||
*/
|
||||
export function projectOntoRoute(p: LatLng, line: LatLng[]): CorridorHit | null {
|
||||
if (line.length < 2) return null
|
||||
let best = Number.POSITIVE_INFINITY
|
||||
let bestAlong = 0
|
||||
let travelled = 0
|
||||
for (let i = 0; i < line.length - 1; i++) {
|
||||
const a = line[i]
|
||||
const b = line[i + 1]
|
||||
const segment = haversineKm(a, b)
|
||||
const { distanceKm: d, t } = projectOnSegment(p, a, b)
|
||||
if (d < best) {
|
||||
best = d
|
||||
bestAlong = travelled + t * segment
|
||||
}
|
||||
travelled += segment
|
||||
}
|
||||
return { offRouteKm: best, alongKm: bestAlong }
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounding boxes covering the route, each no larger than `maxSpanDeg`.
|
||||
*
|
||||
* The server clamps any box bigger than that (MAX_BBOX_SPAN_DEG) so Overpass is not
|
||||
* asked to scan a continent, which means a long drive has to be cut into boxes here
|
||||
* rather than sent as one. Boxes are grown along the route until one would exceed the
|
||||
* span, so a straight motorway needs far fewer requests than a mountain road.
|
||||
*/
|
||||
export function corridorTiles(line: LatLng[], widthKm: number, maxSpanDeg = 0.45): Bbox[] {
|
||||
if (line.length === 0) return []
|
||||
const padLat = widthKm / KM_PER_DEG_LAT
|
||||
const tiles: Bbox[] = []
|
||||
let current: Bbox | null = null
|
||||
|
||||
const padded = (b: Bbox): Bbox => {
|
||||
// Longitude degrees shrink towards the poles, so the padding has to grow with
|
||||
// latitude or the corridor is narrower than asked for in the north.
|
||||
const midLat = (b.north + b.south) / 2
|
||||
const padLng = padLat / Math.max(0.2, Math.cos(toRad(midLat)))
|
||||
return {
|
||||
south: b.south - padLat,
|
||||
north: b.north + padLat,
|
||||
west: b.west - padLng,
|
||||
east: b.east + padLng,
|
||||
}
|
||||
}
|
||||
|
||||
for (const p of line) {
|
||||
if (!current) {
|
||||
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng }
|
||||
continue
|
||||
}
|
||||
const next: Bbox = {
|
||||
south: Math.min(current.south, p.lat),
|
||||
north: Math.max(current.north, p.lat),
|
||||
west: Math.min(current.west, p.lng),
|
||||
east: Math.max(current.east, p.lng),
|
||||
}
|
||||
const grown = padded(next)
|
||||
if (grown.north - grown.south > maxSpanDeg || grown.east - grown.west > maxSpanDeg) {
|
||||
tiles.push(padded(current))
|
||||
current = { south: p.lat, north: p.lat, west: p.lng, east: p.lng }
|
||||
} else {
|
||||
current = next
|
||||
}
|
||||
}
|
||||
if (current) tiles.push(padded(current))
|
||||
return tiles
|
||||
}
|
||||
|
||||
/**
|
||||
* Thins a route down to the points that still describe it, so the corridor is built
|
||||
* from tens of coordinates rather than the thousands a routed geometry carries.
|
||||
* Ramer-Douglas-Peucker with the tolerance expressed in kilometres.
|
||||
*/
|
||||
export function simplifyLine(line: LatLng[], toleranceKm: number): LatLng[] {
|
||||
if (line.length < 3) return line.slice()
|
||||
let maxDist = 0
|
||||
let index = 0
|
||||
const first = line[0]
|
||||
const last = line[line.length - 1]
|
||||
for (let i = 1; i < line.length - 1; i++) {
|
||||
const d = distanceToSegmentKm(line[i], first, last)
|
||||
if (d > maxDist) {
|
||||
maxDist = d
|
||||
index = i
|
||||
}
|
||||
}
|
||||
if (maxDist <= toleranceKm) return [first, last]
|
||||
const left = simplifyLine(line.slice(0, index + 1), toleranceKm)
|
||||
const right = simplifyLine(line.slice(index), toleranceKm)
|
||||
return [...left.slice(0, -1), ...right]
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { mapsApi } from '../../api/client'
|
||||
import { useTranslation } from '../../i18n'
|
||||
import { corridorTiles, projectOntoRoute, simplifyLine, type LatLng } from './corridor'
|
||||
import type { Poi } from '../Map/poiCategories'
|
||||
|
||||
/** A POI that is actually on the way, with the two numbers that make it one. */
|
||||
export interface CorridorPoi extends Poi {
|
||||
offRouteKm: number
|
||||
alongKm: number
|
||||
}
|
||||
|
||||
export interface CorridorSearch {
|
||||
results: CorridorPoi[]
|
||||
/** Areas answered so far, out of how many the route was cut into. */
|
||||
progress: { done: number; total: number }
|
||||
loading: boolean
|
||||
/** True when the route was longer than the request budget and the tail was left out. */
|
||||
capped: boolean
|
||||
error: boolean
|
||||
search: () => void
|
||||
clear: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* How many bounding boxes one search may ask Overpass for. A German-to-Italian drive
|
||||
* would otherwise be dozens of requests against a shared public mirror; past this the
|
||||
* search stops and says so rather than quietly covering half the route.
|
||||
*/
|
||||
const MAX_TILES = 10
|
||||
/** Gap between Overpass requests — the public mirrors are a shared resource. */
|
||||
const REQUEST_SPACING_MS = 700
|
||||
|
||||
const sleep = (ms: number, signal: AbortSignal): Promise<void> =>
|
||||
new Promise(resolve => {
|
||||
if (signal.aborted) { resolve(); return }
|
||||
const timer = setTimeout(done, ms)
|
||||
function done(): void {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener('abort', done)
|
||||
resolve()
|
||||
}
|
||||
signal.addEventListener('abort', done, { once: true })
|
||||
})
|
||||
|
||||
/**
|
||||
* "What is on the way" for a drawn route.
|
||||
*
|
||||
* Deliberately manual: the search runs when the user asks for it, never on pan or on
|
||||
* every route change, because each run is several Overpass requests and the mirrors are
|
||||
* shared. Results stay until the categories or the route change.
|
||||
*/
|
||||
export function useCorridorPois(line: LatLng[], categories: string[], widthKm: number): CorridorSearch {
|
||||
const { locale } = useTranslation()
|
||||
const [results, setResults] = useState<CorridorPoi[]>([])
|
||||
const [progress, setProgress] = useState({ done: 0, total: 0 })
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [capped, setCapped] = useState(false)
|
||||
const [error, setError] = useState(false)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const runIdRef = useRef(0)
|
||||
|
||||
const clear = useCallback(() => {
|
||||
abortRef.current?.abort()
|
||||
setResults([])
|
||||
setProgress({ done: 0, total: 0 })
|
||||
setLoading(false)
|
||||
setCapped(false)
|
||||
setError(false)
|
||||
}, [])
|
||||
|
||||
// A changed route or category set makes the old answers wrong, not stale — drop them.
|
||||
const routeKey = line.length ? `${line.length}:${line[0].lat.toFixed(3)},${line[0].lng.toFixed(3)}` : ''
|
||||
const catKey = categories.join(',')
|
||||
useEffect(() => { clear() }, [routeKey, catKey, widthKm, clear])
|
||||
|
||||
const search = useCallback(() => {
|
||||
abortRef.current?.abort()
|
||||
if (line.length < 2 || categories.length === 0) return
|
||||
const controller = new AbortController()
|
||||
abortRef.current = controller
|
||||
const runId = ++runIdRef.current
|
||||
|
||||
// Thin the routed geometry first: a corridor built from every vertex would make
|
||||
// hundreds of overlapping boxes out of what a handful describe just as well.
|
||||
const spine = simplifyLine(line, Math.max(1, widthKm / 3))
|
||||
const allTiles = corridorTiles(spine, widthKm)
|
||||
const tiles = allTiles.slice(0, MAX_TILES)
|
||||
|
||||
setCapped(allTiles.length > tiles.length)
|
||||
setError(false)
|
||||
setResults([])
|
||||
setLoading(true)
|
||||
setProgress({ done: 0, total: tiles.length * categories.length })
|
||||
|
||||
void (async () => {
|
||||
const seen = new Map<string, CorridorPoi>()
|
||||
let failures = 0
|
||||
let done = 0
|
||||
for (const tile of tiles) {
|
||||
for (const category of categories) {
|
||||
if (controller.signal.aborted || runId !== runIdRef.current) return
|
||||
try {
|
||||
const data = await mapsApi.pois(category, tile, locale, controller.signal)
|
||||
for (const poi of data.pois) {
|
||||
if (seen.has(poi.osm_id)) continue
|
||||
const hit = projectOntoRoute({ lat: poi.lat, lng: poi.lng }, spine)
|
||||
if (!hit || hit.offRouteKm > widthKm) continue
|
||||
seen.set(poi.osm_id, { ...poi, offRouteKm: hit.offRouteKm, alongKm: hit.alongKm })
|
||||
}
|
||||
} catch {
|
||||
// One dead mirror or one clamped box must not empty the whole search; the
|
||||
// run is only called a failure if every request failed.
|
||||
failures++
|
||||
}
|
||||
done++
|
||||
if (controller.signal.aborted || runId !== runIdRef.current) return
|
||||
setProgress({ done, total: tiles.length * categories.length })
|
||||
setResults([...seen.values()].sort((a, b) => a.alongKm - b.alongKm))
|
||||
await sleep(REQUEST_SPACING_MS, controller.signal)
|
||||
}
|
||||
}
|
||||
if (controller.signal.aborted || runId !== runIdRef.current) return
|
||||
setError(failures === tiles.length * categories.length && failures > 0)
|
||||
setLoading(false)
|
||||
})()
|
||||
}, [line, categories, widthKm, locale])
|
||||
|
||||
useEffect(() => () => abortRef.current?.abort(), [])
|
||||
|
||||
return { results, progress, loading, capped, error, search, clear }
|
||||
}
|
||||
Reference in New Issue
Block a user