feat(tours): mark the best known places along a city walk

A search for sights along a tour now also asks the places index for the best
known places near the line, ranked by how often their Wikipedia articles are
read (QRank). A row the index already found is marked as a highlight; a
famous sight no kind names, like a square, is added as a sight of its own.
Stations, hotels and restaurants rank a row they match but are never added.

Highlights are listed first with a star in the list and a badge in the map
card. A place counts as a highlight from 40000 views a year, or the best
three from 5000 where fewer reach that. An index without ranks, or one older
than the endpoint, leaves the search as it was.
This commit is contained in:
Maurice
2026-10-20 12:16:11 +02:00
parent 54baf85a2a
commit 71fe69c1f1
45 changed files with 840 additions and 26 deletions
+10
View File
@@ -30,6 +30,7 @@ import {
trekPlacesArea,
trekPlacesNearby,
toPlaceRecord,
type TrekHighlight,
type TrekPlace,
} from './trek-places.client';
import { InjectRepository } from '@mikro-orm/nestjs';
@@ -252,6 +253,15 @@ export class MapsService {
return this.along.search({ categories, line, corridorM, lang, limit }, this.trekPlacesEnabled());
}
/**
* The best known places near a line, from the index's OpenStreetMap layer in
* the same circles as {@link poisAlong}. None when the index is switched off
* or cannot be asked: highlights add to a search, they never fail it.
*/
highlightsAlong(line: { lat: number; lng: number }[], corridorM: number, lang?: string): Promise<TrekHighlight[]> {
return this.along.highlights(line, corridorM, lang, this.trekPlacesEnabled());
}
// ── Keys and the keyed provider (resolved by PlacesProviderSelector) ─────
/** The Places credential for this request and where it came from (#1939). */
+46 -1
View File
@@ -28,13 +28,16 @@ import {
} from './maps-index.helpers';
import type { OverpassPoi } from './maps.helpers';
import { OsmClient, OverpassCoolingDown } from './providers/osm.client';
import { trekPlacesNearby } from './trek-places.client';
import { trekPlacesHighlights, trekPlacesNearby, type TrekHighlight, type TrekHighlights } from './trek-places.client';
import { Injectable } from '@nestjs/common';
import type { LatLng } from '@trek/shared/roadtrip';
/** How many index requests are in flight at once, so one search never floods the service. */
const PARALLEL_INDEX_REQUESTS = 8;
/** The most well known places one circle is asked for: the best known come first, so a few are plenty. */
const HIGHLIGHTS_PER_CIRCLE = 20;
/** How many stretches one source asks Overpass for at once, so the public mirrors are not flooded. */
const PARALLEL_OVERPASS_STRETCHES = 3;
@@ -148,6 +151,48 @@ export class PoisAlongResolver {
};
}
/**
* The best known places near a line, from the index's OpenStreetMap layer in
* the same circles the kinds are asked in, each place once. Highlights only
* add to a search: an index switched off, down or without ranks answers
* none, logged once, and never fails the search they were asked beside.
*/
async highlights(
line: LatLng[],
corridorM: number,
lang: string | undefined,
indexEnabled: boolean,
): Promise<TrekHighlight[]> {
if (!indexEnabled) return [];
const plan = alongPlan(line, corridorM);
const perCircle = { limit: HIGHLIGHTS_PER_CIRCLE, lang };
const batches = Array.from({ length: Math.ceil(plan.beads.length / PARALLEL_INDEX_REQUESTS) }, (_, index) =>
plan.beads.slice(index * PARALLEL_INDEX_REQUESTS, (index + 1) * PARALLEL_INDEX_REQUESTS),
);
// A few circles at a time, each batch after the last, as the kinds are asked.
const settled = await batches.reduce<Promise<PromiseSettledResult<TrekHighlights>[]>>(
async (done, batch) => [
...(await done),
...(await Promise.allSettled(
batch.map((bead) => trekPlacesHighlights(bead.lat, bead.lng, { ...perCircle, radius: bead.radiusM })),
)),
],
Promise.resolve([]),
);
const found = new Map<string, TrekHighlight>();
const failure = settled.find((entry): entry is PromiseRejectedResult => entry.status === 'rejected');
for (const entry of settled) {
if (entry.status === 'fulfilled') {
for (const row of entry.value.highlights) {
const key = `${row.osmType}:${row.osmId}`;
if (!found.has(key)) found.set(key, row);
}
}
}
if (failure) logWarn(`[Maps] TREK places highlights along a line: ${reason(failure.reason)}`);
return [...found.values()];
}
/** The index kinds in every circle, a few requests at a time; a failed request leaves the others. */
private async askIndex(kinds: string[], plan: AlongPlan, limit: number): Promise<SourceAnswer> {
// No kinds make no plan, and so no request.
@@ -15,6 +15,8 @@ import { readEnv, getAppUrl } from '../../app-config';
import { toApiLang } from './maps.helpers';
import { normalizePlaceWebsite } from '@trek/shared';
import { z } from 'zod';
/** The public instance. An operator may point at their own copy instead. */
export const DEFAULT_TREK_PLACES_URL = 'https://places.liketrek.com';
@@ -452,6 +454,93 @@ export async function trekPlacesNearby(
return Array.isArray(body.results) ? body.results : [];
}
/**
* The bounds of one /v1/highlights request, as the service takes them: a
* request outside them is refused with a 422, so one is clamped to fit before
* it leaves, and a coordinate that is no coordinate is not asked at all.
*/
const HIGHLIGHTS_MIN_RADIUS_M = 10;
const HIGHLIGHTS_MAX_RADIUS_M = 20_000;
const HIGHLIGHTS_DEFAULT_RADIUS_M = 1000;
const HIGHLIGHTS_MAX_LIMIT = 100;
const HIGHLIGHTS_DEFAULT_LIMIT = 30;
/**
* One well known place of the service's OpenStreetMap layer: a row with a
* Wikidata item that QRank ranks, `qrank` its page views. `name` is in the
* language asked where the layer has it, else the local one.
*/
const trekHighlightSchema = z.object({
osmType: z.enum(['node', 'way', 'relation']),
osmId: z.number().int().positive(),
name: z.string().trim().min(1),
lat: z.number().min(-90).max(90),
lng: z.number().min(-180).max(180),
category: z.string().nullable(),
osmTag: z.string(),
wikidata: z.string().regex(/^Q\d+$/),
qrank: z.number().int().nonnegative(),
distanceMetres: z.number().nonnegative(),
});
export type TrekHighlight = z.infer<typeof trekHighlightSchema>;
export interface TrekHighlights {
highlights: TrekHighlight[];
/** The QRank release the ranks are from, or null when the service does not say. */
qrankRelease: string | null;
}
/** A whole number within the bounds; anything that is no number takes the lower one. */
const clampedInt = (value: number, min: number, max: number) =>
Number.isFinite(value) ? Math.min(max, Math.max(min, Math.round(value))) : min;
/**
* The service's answer as rows TREK can trust: a row of another shape is
* dropped on its own rather than failing the others, since the layer is read
* beside the rest of a search and a broken row should cost that row only.
*/
function readHighlights(body: unknown): TrekHighlights {
const answer = z
.object({ highlights: z.array(z.unknown()).catch([]), qrankRelease: z.string().nullable().catch(null) })
.catch({ highlights: [], qrankRelease: null })
.parse(body);
const highlights = answer.highlights.flatMap((row) => {
const parsed = trekHighlightSchema.safeParse(row);
return parsed.success ? [parsed.data] : [];
});
return { highlights, qrankRelease: answer.qrankRelease };
}
/**
* The best known places around a coordinate, by QRank and then nearest. An
* older layer without ranks answers an empty list, never an error; a service
* that is down throws like every other call here, and the caller goes on
* without highlights.
*/
export async function trekPlacesHighlights(
lat: number,
lng: number,
opts: { radius?: number; limit?: number; lang?: string } = {},
): Promise<TrekHighlights> {
if (!Number.isFinite(lat) || !Number.isFinite(lng) || Math.abs(lat) > 90 || Math.abs(lng) > 180) {
return { highlights: [], qrankRelease: null };
}
try {
const body = await getJson<unknown>('/v1/highlights', {
lat,
lng,
radius: clampedInt(opts.radius ?? HIGHLIGHTS_DEFAULT_RADIUS_M, HIGHLIGHTS_MIN_RADIUS_M, HIGHLIGHTS_MAX_RADIUS_M),
limit: clampedInt(opts.limit ?? HIGHLIGHTS_DEFAULT_LIMIT, 1, HIGHLIGHTS_MAX_LIMIT),
lang: serviceLang(opts.lang),
});
return readHighlights(body);
} catch (err) {
// A service older than the endpoint knows no highlights, as an old layer knows no ranks.
if ((err as { status?: number }).status === 404) return { highlights: [], qrankRelease: null };
throw err;
}
}
export interface TrekPlacesArea {
count: number;
truncated: boolean;
+158 -16
View File
@@ -11,6 +11,7 @@ import {
plannableTourTypeSchema,
TOUR_POI_LIMIT,
TOUR_POI_MAX_LINE_POINTS,
tourHighlightIds,
type TourPoi,
type TourPoiCategory,
type TourPoiSearchRequest,
@@ -46,13 +47,144 @@ const PER_KIND_LIMIT = 30;
/** Within this many metres, two places of one name are one place mapped twice. */
const SAME_PLACE_M = 60;
type MapsPoi = Awaited<ReturnType<MapsService['poisAlong']>>['pois'][number];
/**
* Within this many metres, a highlight of the very same name is the place a
* row already has: a square's outline and the point on it lie further apart
* than two points of one place do.
*/
const SAME_NAME_M = 500;
function withinSamePlace(a: Pick<TourPoi, 'lat' | 'lng'>, b: { lat: number; lng: number }): boolean {
type MapsPoi = Awaited<ReturnType<MapsService['poisAlong']>>['pois'][number];
type MapsHighlight = Awaited<ReturnType<MapsService['highlightsAlong']>>[number];
function metresApart(a: Pick<TourPoi, 'lat' | 'lng'>, b: { lat: number; lng: number }): number {
const metresPerDegree = 111_320;
const dLat = (a.lat - b.lat) * metresPerDegree;
const dLng = (a.lng - b.lng) * metresPerDegree * Math.cos((a.lat * Math.PI) / 180);
return Math.hypot(dLat, dLng) <= SAME_PLACE_M;
return Math.hypot(dLat, dLng);
}
function withinSamePlace(a: Pick<TourPoi, 'lat' | 'lng'>, b: { lat: number; lng: number }): boolean {
return metresApart(a, b) <= SAME_PLACE_M;
}
/** A name as compared: without case, accents or punctuation. */
function nameKey(name: string): string {
return name
.normalize('NFD')
.replace(/\p{M}/gu, '')
.toLocaleLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, ' ')
.trim();
}
/**
* Every word of one name is in the other, as "Basilica San Marco" is in
* "Basilica di San Marco", or they share at least two words and half of each.
* Whole words only: "Dom" is not "Domplatz", and one shared "Palazzo" does not
* make "Palazzo Ducale" the "Palazzo Reale".
*/
function similarNames(a: string, b: string): boolean {
if (!a || !b) return false;
const words = new Set(a.split(' '));
const others = new Set(b.split(' '));
const shared = [...others].filter((word) => words.has(word)).length;
if (shared === Math.min(words.size, others.size)) return true;
return shared >= 2 && shared * 2 >= Math.max(words.size, others.size);
}
/**
* The row a highlight is already in: the same OpenStreetMap object, the same
* name nearby, or a like name in one spot.
*/
function rowOfHighlight(places: readonly TourPoi[], highlight: MapsHighlight, id: string): TourPoi | undefined {
const name = nameKey(highlight.name);
return places.find((place) => {
if (place.id === id) return true;
const other = nameKey(place.name);
const apart = metresApart(place, highlight);
return (!!name && other === name && apart <= SAME_NAME_M) || (apart <= SAME_PLACE_M && similarNames(name, other));
});
}
/**
* The kinds of the index a highlight may come in as a sight of its own. A
* station, a hotel or a restaurant can be famous too, but it is no sight: it
* still ranks a row it matches, and is never added.
*/
const SIGHT_INDEX_CATEGORIES: ReadonlySet<string> = new Set(['sehenswuerdigkeit', 'kultur']);
/**
* The places found with the best known places near the line merged in: a
* highlight a row already has ranks that row, and a sight no row has is added
* when the rule marks it (Piazza San Marco is a square, which no kind asks for).
* A ranked place the rule does not mark is not worth a row of its own. The
* ranks are kept beside the rows, by id, for the highlight rule.
*/
function withHighlights(
places: readonly TourPoi[],
highlights: readonly MapsHighlight[],
corridorM: number,
line: Array<[number, number]>,
): { places: TourPoi[]; ranks: Map<string, number> } {
const merged = [...places];
const candidates: TourPoi[] = [];
const ranks = new Map<string, number>();
for (const highlight of [...highlights].sort((a, b) => b.qrank - a.qrank)) {
const near = nearnessToLine({ lat: highlight.lat, lng: highlight.lng }, line);
if (!near || near.distanceM > corridorM) continue;
const id = `${highlight.osmType}:${highlight.osmId}`;
const row = rowOfHighlight([...merged, ...candidates], highlight, id);
if (row) {
ranks.set(row.id, Math.max(ranks.get(row.id) ?? 0, highlight.qrank));
continue;
}
if (!highlight.category || !SIGHT_INDEX_CATEGORIES.has(highlight.category)) continue;
candidates.push({
id,
name: highlight.name,
lat: highlight.lat,
lng: highlight.lng,
category: 'sights',
kind: highlight.osmTag,
source: 'openstreetmap',
address: null,
website: null,
phone: null,
opening_hours: null,
distance_m: Math.round(near.distanceM),
along_m: Math.round(near.alongM),
});
ranks.set(id, highlight.qrank);
}
const marked = new Set(tourHighlightIds([...ranks].map(([id, qrank]) => ({ id, qrank }))));
for (const candidate of candidates) {
if (marked.has(candidate.id)) merged.push(candidate);
else ranks.delete(candidate.id);
}
return { places: merged, ranks };
}
/**
* The answer's rows: the highlights first, best known first, then the nearest
* of the rest to the line, in the order the tour meets them. A highlight is
* never cut for a nearer place.
*/
function answerRows(places: readonly TourPoi[], ranks: ReadonlyMap<string, number>): TourPoi[] {
const marked = new Set(tourHighlightIds([...ranks].map(([id, qrank]) => ({ id, qrank }))));
const rank = (place: TourPoi) => ranks.get(place.id) ?? 0;
const highlights = places
.filter((place) => marked.has(place.id))
.sort((a, b) => rank(b) - rank(a))
.slice(0, TOUR_POI_LIMIT)
.map((place) => ({ ...place, highlight: true }));
// The nearest to the line when there are too many, then in the order the tour meets them.
const rest = places
.filter((place) => !marked.has(place.id))
.sort((a, b) => a.distance_m - b.distance_m)
.slice(0, TOUR_POI_LIMIT - highlights.length)
.sort((a, b) => a.along_m - b.along_m || a.distance_m - b.distance_m);
return [...highlights, ...rest];
}
function tourCategoryOf(mapsCategory: string, asked: readonly TourPoiCategory[]): TourPoiCategory | undefined {
@@ -104,7 +236,8 @@ function placesWithin(found: MapsPoi[], body: TourPoiSearchRequest, line: Array<
* answer carries, listed from the start. Nothing is written. A kind no source
* could be asked for is named as unavailable, so a failed source never reads
* as nothing found; the distance is measured straight across to the line,
* never a way someone walked or paddled.
* never a way someone walked or paddled. A search for sights also asks for the
* best known places near the line and lists its highlights first.
*/
@Injectable()
export class TourPoiSearchService {
@@ -117,20 +250,17 @@ export class TourPoiSearchService {
async search(body: TourPoiSearchRequest): Promise<TourPoiSearchResponse> {
// The contract's tuples, spelled out as pairs once for the measures below.
const line = body.line.map((point): [number, number] => [Number(point[0]), Number(point[1])]);
const points = line.map(([lat, lng]) => ({ lat, lng }));
const asked = [...new Set(body.categories.flatMap((category) => MAPS_CATEGORIES[category]))];
const along = await this.maps.poisAlong(
asked,
line.map(([lat, lng]) => ({ lat, lng })),
body.corridor_m,
body.lang,
PER_KIND_LIMIT,
);
const places = placesWithin(along.pois, body, line);
// The nearest to the line when there are too many, then in the order the tour meets them.
const nearest = [...places].sort((a, b) => a.distance_m - b.distance_m).slice(0, TOUR_POI_LIMIT);
// The best known places are what a search for sights is for, on any tour.
const [along, highlights] = await Promise.all([
this.maps.poisAlong(asked, points, body.corridor_m, body.lang, PER_KIND_LIMIT),
body.categories.includes('sights') ? this.highlightsAlong(points, body) : [],
]);
const found = withHighlights(placesWithin(along.pois, body, line), highlights, body.corridor_m, line);
return {
pois: nearest.sort((a, b) => a.along_m - b.along_m || a.distance_m - b.distance_m),
truncated: along.truncated || places.length > TOUR_POI_LIMIT,
pois: answerRows(found.places, found.ranks),
truncated: along.truncated || found.places.length > TOUR_POI_LIMIT,
partial: along.partial,
capped: along.capped,
unavailable: body.categories.filter((category) =>
@@ -139,6 +269,18 @@ export class TourPoiSearchService {
};
}
/** The best known places near the line, or none when they cannot be had: they add to a search, never fail it. */
private async highlightsAlong(
points: Array<{ lat: number; lng: number }>,
body: TourPoiSearchRequest,
): Promise<MapsHighlight[]> {
try {
return await this.maps.highlightsAlong(points, body.corridor_m, body.lang);
} catch {
return [];
}
}
/** The same search along a saved tour's line, for a client that has no draft (MCP). */
async searchSavedTour(
tripId: number,
+1 -1
View File
@@ -190,7 +190,7 @@ export class ToursMcp {
@Tool({
name: 'search_tour_pois',
description:
'Search places along the saved line of a tour: what a hike, a bike tour, a paddle tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. A tour saved with its points only (route_pending) has no line to search along yet. Nothing is added to the tour or the trip.',
'Search places along the saved line of a tour: what a hike, a bike tour, a paddle tour or a city walk stops for (viewpoint, peak, shelter, drinking_water, food, toilets, picnic, campsite, sights, slipway, boat_rental, bike_repair for repair stations and bike shops, and for a city walk museum for museums and galleries, park for parks and gardens, cafe, restaurant and market), within corridor_m metres of the line. Answers each place with its source (TREK places index or OpenStreetMap), kind, address, website and phone where known, opening hours as the source has them (a hint to check, never a promise), distance_m (straight across to the line, not a detour) and along_m (from the start along the line); up to 60, the nearest to the line when more match, listed from the start. When sights are asked for, the best known places near the line (by the page views of their Wikidata item) are searched too: a square or landmark no category names is added as a sight, and the highlights among them carry highlight: true and come first, the best known first. A place OpenStreetMap has no name for (a tap, a bench) comes with an empty name. unavailable lists the categories no source could be searched for right now: their places are missing, not absent, so ask again later rather than reporting none. partial says some stretches could not be searched, capped that only the first part of a long line was, truncated that more places matched. A tour saved with its points only (route_pending) has no line to search along yet. Nothing is added to the tour or the trip.',
inputSchema: {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),