mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 09:38:54 +00:00
fix(maps): place suggestions name their town and country in the language of the search
The TREK Places service takes an optional lang now and puts localities into it, and names its OpenStreetMap layer rows in it with the settlement they are in. TREK never sent one, so a Japan trip in an English UI kept reading "福岡市博多区" and the layer rows had no place at all, only the local name. Search, autocomplete, nearby and the details of an index place now ask in the reader's language (TREK codes through toApiLang, anything that is no language tag left off). A layer row with a locality reads "Sumida, Japan" like an index row, the country named from its coordinate; without one it keeps the local name as before. The offline area download stays without a language. REST and MCP share the service methods, so both get it. Refs #2592
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
* need no branch per source. Pure: the calls themselves are trek-places.client's,
|
||||
* the decision to make them is MapsService's.
|
||||
*/
|
||||
import { getCountryFromCoords } from '../atlas/atlas-geo';
|
||||
import { buildOsmDetails, parsePoiCategories, samePlace, toApiLang } from './maps.helpers';
|
||||
import { POI_RESULT_CAP, type PoiSearchResult } from './providers/osm.client';
|
||||
import {
|
||||
@@ -96,11 +97,11 @@ export function indexPoiPlan(category: string, bbox: PoiBbox, limit: number): In
|
||||
* this branch argues elsewhere that naming a source is a licence obligation. The
|
||||
* wire contract keeps `source` an open string, so widening it costs nothing.
|
||||
*
|
||||
* One thing the index cannot do is localise. The Overpass path picks
|
||||
* `name:<lang>` and falls back to `int_name`; the service has no language
|
||||
* parameter at all, so a German user exploring Tokyo gets the Japanese primary
|
||||
* names here. Named rather than hidden: whoever adds localisation upstream
|
||||
* should find this comment.
|
||||
* One thing the index cannot do is translate a name. The Overpass path picks
|
||||
* `name:<lang>` and falls back to `int_name`; the service takes a language now,
|
||||
* but only puts localities into it, because Overture carries no translated
|
||||
* names. A German user exploring Tokyo therefore still gets the Japanese
|
||||
* primary names here, and the POI pins show no locality to translate.
|
||||
*/
|
||||
export function indexPoiAnswer(
|
||||
found: (TrekPlace & { categoryPath?: string | null })[],
|
||||
@@ -195,10 +196,18 @@ export function indexSuggestions(found: TrekSearchHit[], lang?: string): MapsAut
|
||||
// the failure would land after the user had picked it.
|
||||
placeId: osmPlaceId(p),
|
||||
mainText: p.name,
|
||||
// The layer carries no address. The local name is what the
|
||||
// place is called on the spot, which is more use under a
|
||||
// translated label than an empty line.
|
||||
secondaryText: p.local_name && p.local_name !== p.name ? p.local_name : '',
|
||||
// The layer carries no address, but asked with a language it
|
||||
// names the town the place is in, and that reads the way an
|
||||
// index row does: "Sumida, Japan" (#2592). The country comes
|
||||
// from the coordinate, which is all the layer has. Without a
|
||||
// locality the local name is what the place is called on the
|
||||
// spot, which is more use under a translated label than an
|
||||
// empty line.
|
||||
secondaryText: p.locality
|
||||
? [p.locality, countryName(getCountryFromCoords(p.lat, p.lng), lang)].filter(Boolean).join(', ')
|
||||
: p.local_name && p.local_name !== p.name
|
||||
? p.local_name
|
||||
: '',
|
||||
// Per row, because this list is two indexes interleaved.
|
||||
// The name above the list says `trek-places`, which is true
|
||||
// of the call and false of half the rows in it — the layer
|
||||
|
||||
@@ -355,6 +355,7 @@ export class MapsService {
|
||||
lat: locationBias?.lat,
|
||||
lng: locationBias?.lng,
|
||||
limit: 10,
|
||||
lang,
|
||||
})
|
||||
.then(indexHitsOnly)
|
||||
.catch((err: unknown) => {
|
||||
@@ -446,7 +447,7 @@ export class MapsService {
|
||||
const keyed = await this.keyedProvider(userId);
|
||||
if (this.trekPlacesEnabled() && !(await this.selector.googleOnly(keyed))) {
|
||||
// Never throws upward, like the search: a slow index drops to the next source.
|
||||
const found = await trekPlacesNearby(origin.lat, origin.lng, { radius, limit }).catch((err: unknown) => {
|
||||
const found = await trekPlacesNearby(origin.lat, origin.lng, { radius, limit, lang }).catch((err: unknown) => {
|
||||
console.warn('TREK Places nearby failed, falling back:', (err as Error).message);
|
||||
return [];
|
||||
});
|
||||
@@ -519,6 +520,7 @@ export class MapsService {
|
||||
lng: centre?.lng,
|
||||
limit: 8,
|
||||
sources: 'index,osm',
|
||||
lang,
|
||||
});
|
||||
if (found.length > 0) return { suggestions: indexSuggestions(found, lang), source: 'trek-places' };
|
||||
} catch (err: unknown) {
|
||||
|
||||
@@ -58,7 +58,9 @@ export class PlaceDetailsResolver {
|
||||
// the index: a place saved while it was on is still opened from what the
|
||||
// trip holds, not looked up again.
|
||||
if (!indexEnabled) return { place: null };
|
||||
const found = await trekPlacesById(placeId.slice('gers:'.length)).catch(() => null);
|
||||
// In the reader's language, so the locality the place is saved with is
|
||||
// one they can read (#2592). The name stays what the index has.
|
||||
const found = await trekPlacesById(placeId.slice('gers:'.length), { lang }).catch(() => null);
|
||||
if (!found) return { place: null };
|
||||
|
||||
// What the index lacks, OpenStreetMap often has for the same building
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
* and the service being down, both of which fall back to what TREK did before.
|
||||
*/
|
||||
import { readEnv, getAppUrl } from '../../app-config';
|
||||
import { toApiLang } from './maps.helpers';
|
||||
import { normalizePlaceWebsite } from '@trek/shared';
|
||||
|
||||
/** The public instance. An operator may point at their own copy instead. */
|
||||
@@ -219,6 +220,26 @@ async function getJson<T>(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The reader's language in the form the service takes, or nothing.
|
||||
*
|
||||
* Optional on every call that returns places: without it the service answers
|
||||
* exactly as it did before it knew languages. With it, localities come back in
|
||||
* the reader's language where OpenStreetMap has one, and the OSM layer's rows
|
||||
* are named in it too (#2592). TREK's own codes go through toApiLang first
|
||||
* (`br` is Brazilian Portuguese here and Breton there). Anything that is still
|
||||
* not a language tag is left off rather than sent: the service refuses it with
|
||||
* a 422, and a refused keystroke would drop to the fallback for nothing.
|
||||
* Regional Chinese (`zh-TW`) is passed as it is; the service maps it onto the
|
||||
* script OpenStreetMap keys by.
|
||||
*/
|
||||
const SERVICE_LANG = /^[A-Za-z]{2,3}([_-][A-Za-z0-9]{2,8}){0,2}$/;
|
||||
export function serviceLang(lang: string | undefined): string | undefined {
|
||||
if (!lang?.trim()) return undefined;
|
||||
const tag = toApiLang(lang);
|
||||
return tag.length <= 20 && SERVICE_LANG.test(tag) ? tag : undefined;
|
||||
}
|
||||
|
||||
async function readCapped(res: Response, max: number): Promise<string> {
|
||||
const reader = res.body?.getReader();
|
||||
if (!reader) return res.text();
|
||||
@@ -249,7 +270,9 @@ async function readCapped(res: Response, max: number): Promise<string> {
|
||||
*
|
||||
* It has no address block. OpenStreetMap does not carry one per node, and
|
||||
* inventing an empty one here would let a caller read `address.locality` and
|
||||
* quietly get nothing.
|
||||
* quietly get nothing. What it does carry, when the search was made with a
|
||||
* language, is `locality`: the settlement the place is in, named in that
|
||||
* language. Without a language the field is absent, as it always was.
|
||||
*/
|
||||
export interface TrekOsmPlace {
|
||||
/** Always `osm:<type>/<id>`, e.g. `osm:node/9712313`. */
|
||||
@@ -262,6 +285,7 @@ export interface TrekOsmPlace {
|
||||
lng: number;
|
||||
category: string | null;
|
||||
source: 'openstreetmap';
|
||||
locality?: string | null;
|
||||
distance_km?: number;
|
||||
}
|
||||
|
||||
@@ -281,9 +305,20 @@ export function osmPlaceId(hit: TrekOsmPlace): string {
|
||||
return `${hit.osm_type}:${hit.osm_id}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer's `locality` as a name or null. It is the one field of that row
|
||||
* TREK prints as it came, so a number, an object or a blank from a broken
|
||||
* upstream must not reach the suggestion line.
|
||||
*/
|
||||
function withLocality(hit: TrekSearchHit): TrekSearchHit {
|
||||
if (!isOsmHit(hit) || hit.locality === undefined) return hit;
|
||||
const locality = typeof hit.locality === 'string' ? hit.locality.trim() : '';
|
||||
return { ...hit, locality: locality || null };
|
||||
}
|
||||
|
||||
export async function trekPlacesSearch(
|
||||
query: string,
|
||||
opts: { lat?: number; lng?: number; limit?: number; sources?: string } = {},
|
||||
opts: { lat?: number; lng?: number; limit?: number; sources?: string; lang?: string } = {},
|
||||
): Promise<TrekSearchHit[]> {
|
||||
const body = await getJson<{ results?: TrekSearchHit[] }>('/v1/search', {
|
||||
q: query,
|
||||
@@ -295,8 +330,9 @@ export async function trekPlacesSearch(
|
||||
// wants: the explicit search path already asks Nominatim in parallel, and
|
||||
// adding the layer there would return the same OpenStreetMap places twice.
|
||||
sources: opts.sources,
|
||||
lang: serviceLang(opts.lang),
|
||||
});
|
||||
return Array.isArray(body.results) ? body.results : [];
|
||||
return Array.isArray(body.results) ? body.results.map(withLocality) : [];
|
||||
}
|
||||
|
||||
/** The index-only rows of a mixed result, for callers that need Overture fields. */
|
||||
@@ -346,7 +382,7 @@ export interface TrekNearbyPlace extends TrekPlace {
|
||||
export async function trekPlacesNearby(
|
||||
lat: number,
|
||||
lng: number,
|
||||
opts: { radius?: number; limit?: number; category?: string } = {},
|
||||
opts: { radius?: number; limit?: number; category?: string; lang?: string } = {},
|
||||
): Promise<TrekNearbyPlace[]> {
|
||||
const body = await getJson<{ results: TrekNearbyPlace[] }>('/v1/nearby', {
|
||||
lat,
|
||||
@@ -354,6 +390,7 @@ export async function trekPlacesNearby(
|
||||
radius: Math.round(opts.radius ?? 1500),
|
||||
limit: opts.limit ?? 50,
|
||||
category: opts.category,
|
||||
lang: serviceLang(opts.lang),
|
||||
});
|
||||
return Array.isArray(body.results) ? body.results : [];
|
||||
}
|
||||
@@ -372,6 +409,9 @@ export interface TrekPlacesArea {
|
||||
* are its call, not ours, and a `truncated` answer is passed through honestly
|
||||
* rather than smoothed over. A client that believed it had the whole area would
|
||||
* search offline and quietly miss places.
|
||||
*
|
||||
* No language here, on purpose: the offline package is stored once per trip and
|
||||
* read in whatever language the app is in later, and its contract carries none.
|
||||
*/
|
||||
export async function trekPlacesArea(
|
||||
bbox: { minLat: number; minLng: number; maxLat: number; maxLng: number },
|
||||
@@ -392,9 +432,11 @@ export async function trekPlacesArea(
|
||||
};
|
||||
}
|
||||
|
||||
export async function trekPlacesById(gers: string): Promise<TrekPlace | null> {
|
||||
export async function trekPlacesById(gers: string, opts: { lang?: string } = {}): Promise<TrekPlace | null> {
|
||||
try {
|
||||
const body = await getJson<{ place: TrekPlace }>(`/v1/place/${encodeURIComponent(gers)}`, {});
|
||||
const body = await getJson<{ place: TrekPlace }>(`/v1/place/${encodeURIComponent(gers)}`, {
|
||||
lang: serviceLang(opts.lang),
|
||||
});
|
||||
return body.place ?? null;
|
||||
} catch (err) {
|
||||
if ((err as { status?: number }).status === 404) return null;
|
||||
|
||||
Reference in New Issue
Block a user