mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 03:26:07 +00:00
feat(server): ask the TREK services' Photon before Nominatim for search and reverse lookups
An installation that holds a key for the TREK services and has no NOMINATIM_URL of its own now sends the OpenStreetMap search and the reverse lookups to photon.liketrek.com first. The answers are read into Nominatim's shape, so the place records stay the same, and every miss (refused key, allowance spent, timeout, error, foreign body) falls back to Nominatim, with a one minute pause after four misses in a row. TREK_PHOTON_URL points at another copy, and the default of TREK_SERVICES_HOSTS now lists photon.liketrek.com and valhalla.liketrek.com beside places.liketrek.com.
This commit is contained in:
@@ -63,7 +63,10 @@ export function deriveKitinerary(raw: RawEnv) {
|
||||
}
|
||||
|
||||
/** The liketrek hosts that receive the installation key when nothing else is configured. */
|
||||
const DEFAULT_SERVICE_HOSTS = ['places.liketrek.com'];
|
||||
const DEFAULT_SERVICE_HOSTS = ['places.liketrek.com', 'photon.liketrek.com', 'valhalla.liketrek.com'];
|
||||
|
||||
/** The address search of the TREK services, asked before Nominatim while the installation holds a key. */
|
||||
const DEFAULT_PHOTON_URL = 'https://photon.liketrek.com';
|
||||
|
||||
/**
|
||||
* How this installation identifies itself to the liketrek services. Unset is
|
||||
@@ -77,6 +80,7 @@ export function deriveServices(raw: RawEnv) {
|
||||
mode: mode === 'auto' ? ('auto' as const) : ('off' as const),
|
||||
key: raw.TREK_SERVICES_KEY?.trim() || null,
|
||||
hosts: hosts?.length ? hosts : DEFAULT_SERVICE_HOSTS,
|
||||
photonUrl: stripTrailingSlashes(raw.TREK_PHOTON_URL?.trim() || DEFAULT_PHOTON_URL),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -284,6 +284,8 @@ export function deriveIntegrations(raw: RawEnv) {
|
||||
// treats a blank one as unset, so a padded or whitespace-only value would
|
||||
// otherwise pass startup and then be the string that cannot be fetched.
|
||||
nominatimUrl: stripTrailingSlashes(raw.NOMINATIM_URL?.trim() || 'https://nominatim.openstreetmap.org'),
|
||||
/** The operator runs a geocoder of their own, so search and reverse stay on it instead of going to Photon. */
|
||||
nominatimOwn: Boolean(raw.NOMINATIM_URL?.trim()),
|
||||
overpassUrl: raw.OVERPASS_URL,
|
||||
// Longer than the `[timeout:20]` the query itself carries, or we abort an answer the
|
||||
// mirror was still allowed to be working on. See OVERPASS_QUERY_TIMEOUT_S.
|
||||
|
||||
@@ -188,6 +188,7 @@ export const envSchema = z.object({
|
||||
TREK_SERVICES: oneOf(['auto', 'off']),
|
||||
TREK_SERVICES_KEY: optionalWith(isServiceKeyShape, 'must be a TREK services key (tk1.<kid>.<payload>.<signature>)'),
|
||||
TREK_SERVICES_HOSTS: anyString,
|
||||
TREK_PHOTON_URL: url,
|
||||
PLACES_API_KEY: anyString,
|
||||
AMAP_API_BASE: url,
|
||||
AMAP_API_KEY: anyString,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { AppSettings } from '../../db/entities/AppSettings.entity';
|
||||
import { PlaceDetailsCache } from '../../db/entities/PlaceDetailsCache.entity';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { GoogleQuotaModule } from '../google-quota/google-quota.module';
|
||||
import { PlacePhotosModule } from '../place-photos/place-photos.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
@@ -15,6 +16,7 @@ import { PlacesProviderSelector } from './places-provider.selector';
|
||||
import { PoisAlongResolver } from './pois-along.resolver';
|
||||
import { GooglePlacesClient } from './providers/google-places.provider';
|
||||
import { OsmClient } from './providers/osm.client';
|
||||
import { PhotonClient } from './providers/photon.client';
|
||||
import { WikimediaClient } from './providers/wikimedia.client';
|
||||
import { TrekPlacesLayersService } from './trek-places-layers.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
@@ -26,7 +28,8 @@ import { Module } from '@nestjs/common';
|
||||
* MapsService is the orchestrator every consumer injects (BookingImportModule's
|
||||
* geocoding, PlacesModule's search_place tool and list-import enrichment, the
|
||||
* road trip search). Behind it sit one provider per outbound source
|
||||
* (GooglePlacesClient, OsmClient, WikimediaClient; Amap is built per request by
|
||||
* (GooglePlacesClient, OsmClient with the PhotonClient it asks before
|
||||
* Nominatim, WikimediaClient; Amap is built per request by
|
||||
* PlacesProviderSelector) and the resolvers it delegates to. The three clients
|
||||
* are exported too, so the enrichment column asks Google, OpenStreetMap and
|
||||
* Wikimedia directly rather than through a MapsService facade, and
|
||||
@@ -34,7 +37,8 @@ import { Module } from '@nestjs/common';
|
||||
* routes layers before it asks the Overpass mirrors. Nothing outside
|
||||
* the container consumes this domain, so there is no bridge.
|
||||
*
|
||||
* MikroOrmModule.forFeature: AppSettings and Users for the key chain
|
||||
* AppConfigModule for the servicesConfig token PhotonClient reads its address
|
||||
* from. MikroOrmModule.forFeature: AppSettings and Users for the key chain
|
||||
* (instance-api-keys.ts's resolveApiKey) and the kill switches,
|
||||
* PlaceDetailsCache for the details cache (the entity only, not
|
||||
* place-enrichment's module, so there is no new module edge) and Places for the
|
||||
@@ -42,6 +46,7 @@ import { Module } from '@nestjs/common';
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
PlacePhotosModule,
|
||||
StorageModule,
|
||||
GoogleQuotaModule,
|
||||
@@ -53,6 +58,7 @@ import { Module } from '@nestjs/common';
|
||||
MapsMcp,
|
||||
GooglePlacesClient,
|
||||
OsmClient,
|
||||
PhotonClient,
|
||||
WikimediaClient,
|
||||
PlacesProviderSelector,
|
||||
PlacePhotoResolver,
|
||||
|
||||
@@ -15,6 +15,12 @@
|
||||
* search along a line takes after every Overpass endpoint failed it is the
|
||||
* instance's own: MapsModule provides one client per process.
|
||||
*
|
||||
* Search and reverse ask Photon first (PhotonClient) where the TREK services
|
||||
* hold a key and the operator runs no Nominatim of their own; its answers are
|
||||
* read into Nominatim's shape, so both come out of the same mapping. Lookups
|
||||
* by id and the identity match stay on Nominatim: they need its id lookup and
|
||||
* its extratags.
|
||||
*
|
||||
* Never imports MapsService: providers sit below the orchestrator
|
||||
* (lint:boundaries holds that).
|
||||
*/
|
||||
@@ -41,6 +47,8 @@ import {
|
||||
} from '../maps.helpers';
|
||||
import { overpassSelector, tagsMatchFilter } from '../osm-filter.helpers';
|
||||
import { OverpassBusy, hedged, lastAnsweredFirst, retryAfterMs, soonestRetryMs } from '../overpass-hedge.helpers';
|
||||
import { PhotonClient } from './photon.client';
|
||||
import { asNominatimHit, asNominatimReverse } from './photon.mapping';
|
||||
import { readWikiIdentity } from './wiki-identity';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { normalizePlaceWebsite } from '@trek/shared';
|
||||
@@ -51,7 +59,7 @@ function nominatimCategory(item: { class?: string; type?: string }): string | nu
|
||||
return item.class === 'shop' ? `shop_${item.type}` : item.type;
|
||||
}
|
||||
|
||||
interface NominatimResult {
|
||||
export interface NominatimResult {
|
||||
osm_type: string;
|
||||
osm_id: string;
|
||||
/** The main OSM tag, key and value: `class` "tourism" with `type` "hotel". */
|
||||
@@ -99,6 +107,35 @@ export interface NominatimReverse {
|
||||
address?: Record<string, string>;
|
||||
}
|
||||
|
||||
/** A search row as TREK's place record. */
|
||||
function searchRecord(item: NominatimResult) {
|
||||
// Number.isFinite, not `|| null`: a place on the equator or prime
|
||||
// meridian has a legitimate 0 coordinate.
|
||||
const lat = Number.parseFloat(item.lat);
|
||||
const lng = Number.parseFloat(item.lon);
|
||||
return {
|
||||
google_place_id: null,
|
||||
google_ftid: null,
|
||||
osm_id: `${item.osm_type}:${item.osm_id}`,
|
||||
name: item.name || item.display_name?.split(',')[0] || '',
|
||||
address: item.display_name || '',
|
||||
lat: Number.isFinite(lat) ? lat : null,
|
||||
lng: Number.isFinite(lng) ? lng : null,
|
||||
rating: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
// What the place is, so the add form can preselect a category (#2282). A shop's
|
||||
// value is the ware ("bakery"), so the key goes first and says it is a shop.
|
||||
category: nominatimCategory(item),
|
||||
source: 'openstreetmap',
|
||||
...readWikiIdentity(item.extratags),
|
||||
};
|
||||
}
|
||||
|
||||
function isHit(hit: NominatimResult | null): hit is NominatimResult {
|
||||
return hit !== null;
|
||||
}
|
||||
|
||||
// Tighter than the wiki calls, because this one sits at the FRONT of a chain:
|
||||
// identity, then sitelinks, then the extract. Nominatim answers a bounded
|
||||
// search in 0.2-0.7s in practice, so anything past a couple of seconds is a bad
|
||||
@@ -402,6 +439,8 @@ export class OsmClient {
|
||||
/** Whether this cooldown's first skip was logged, so the log holds one line per cooldown. */
|
||||
private overpassAlongSkipLogged = false;
|
||||
|
||||
constructor(private readonly photon: PhotonClient) {}
|
||||
|
||||
// ── Nominatim search ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -420,6 +459,8 @@ export class OsmClient {
|
||||
lane: GeoLane = 'interactive',
|
||||
bias?: { lat: number; lng: number },
|
||||
) {
|
||||
const photon = await this.photon.search(query, { lang, bias });
|
||||
if (photon) return photon.map(asNominatimHit).filter(isHit).map(searchRecord);
|
||||
const params = new URLSearchParams({
|
||||
q: query,
|
||||
format: 'json',
|
||||
@@ -450,29 +491,7 @@ export class OsmClient {
|
||||
);
|
||||
}
|
||||
const data = (await response.json()) as NominatimResult[];
|
||||
return data.map((item) => {
|
||||
// Number.isFinite, not `|| null`: a place on the equator or prime
|
||||
// meridian has a legitimate 0 coordinate.
|
||||
const lat = Number.parseFloat(item.lat);
|
||||
const lng = Number.parseFloat(item.lon);
|
||||
return {
|
||||
google_place_id: null,
|
||||
google_ftid: null,
|
||||
osm_id: `${item.osm_type}:${item.osm_id}`,
|
||||
name: item.name || item.display_name?.split(',')[0] || '',
|
||||
address: item.display_name || '',
|
||||
lat: Number.isFinite(lat) ? lat : null,
|
||||
lng: Number.isFinite(lng) ? lng : null,
|
||||
rating: null,
|
||||
website: null,
|
||||
phone: null,
|
||||
// What the place is, so the add form can preselect a category (#2282). A shop's
|
||||
// value is the ware ("bakery"), so the key goes first and says it is a shop.
|
||||
category: nominatimCategory(item),
|
||||
source: 'openstreetmap',
|
||||
...readWikiIdentity(item.extratags),
|
||||
};
|
||||
});
|
||||
return data.map(searchRecord);
|
||||
}
|
||||
|
||||
/** Suggestions out of a Nominatim search, for an install with neither the index nor a key. */
|
||||
@@ -630,13 +649,38 @@ export class OsmClient {
|
||||
|
||||
// ── Nominatim reverse ──────────────────────────────────────────────────────
|
||||
|
||||
/** The name and address Nominatim gives a point, or nulls when it answers with an error. */
|
||||
/** The name and address Photon or Nominatim gives a point, or nulls when Nominatim answers with an error. */
|
||||
async reverse(
|
||||
lat: string,
|
||||
lng: string,
|
||||
lang?: string,
|
||||
opts?: { lane?: GeoLane; timeoutMs?: number; locality?: boolean },
|
||||
): Promise<{ name: string | null; address: string | null }> {
|
||||
const data = (await this.reversePhoton(lat, lng, lang)) ?? (await this.reverseNominatim(lat, lng, lang, opts));
|
||||
if (!data) return { name: null, address: null };
|
||||
const addr = data.address || {};
|
||||
const name = opts?.locality
|
||||
? addr.city || addr.town || addr.village || addr.municipality || data.name || null
|
||||
: data.name || addr.tourism || addr.amenity || addr.shop || addr.building || addr.road || null;
|
||||
return { name, address: data.display_name || null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Photon's nearest feature, or null for Nominatim to answer. Photon looks
|
||||
* within a radius and can find nothing at all, where Nominatim names the
|
||||
* nearest object at any distance, so an empty answer is asked again there.
|
||||
*/
|
||||
private async reversePhoton(lat: string, lng: string, lang?: string): Promise<NominatimReverse | null> {
|
||||
const found = await this.photon.reverse(Number.parseFloat(lat), Number.parseFloat(lng), lang);
|
||||
return found?.[0] ? asNominatimReverse(found[0]) : null;
|
||||
}
|
||||
|
||||
private async reverseNominatim(
|
||||
lat: string,
|
||||
lng: string,
|
||||
lang?: string,
|
||||
opts?: { lane?: GeoLane; timeoutMs?: number; locality?: boolean },
|
||||
): Promise<NominatimReverse | null> {
|
||||
const params = new URLSearchParams({
|
||||
lat,
|
||||
lon: lng,
|
||||
@@ -646,21 +690,18 @@ export class OsmClient {
|
||||
'accept-language': toApiLang(lang),
|
||||
});
|
||||
const response = await nominatimFetch('reverse', params, opts);
|
||||
if (!response.ok) return { name: null, address: null };
|
||||
const data = (await response.json()) as NominatimReverse;
|
||||
const addr = data.address || {};
|
||||
const name = opts?.locality
|
||||
? addr.city || addr.town || addr.village || addr.municipality || data.name || null
|
||||
: data.name || addr.tourism || addr.amenity || addr.shop || addr.building || addr.road || null;
|
||||
return { name, address: data.display_name || null };
|
||||
if (!response.ok) return null;
|
||||
return (await response.json()) as NominatimReverse;
|
||||
}
|
||||
|
||||
/**
|
||||
* The raw reverse answer for a point a pasted link carried, in Nominatim's
|
||||
* default language. A non-ok answer (5xx, 429) is an empty object: the
|
||||
* The raw reverse answer for a point a pasted link carried, in the names
|
||||
* used on the spot. A non-ok answer (5xx, 429) is an empty object: the
|
||||
* coordinates are already known, so the caller still has something to return.
|
||||
*/
|
||||
async reverseRaw(lat: number, lng: number): Promise<NominatimReverse> {
|
||||
const found = await this.photon.reverse(lat, lng);
|
||||
if (found?.[0]) return asNominatimReverse(found[0]);
|
||||
const res = await nominatimFetch(
|
||||
'reverse',
|
||||
new URLSearchParams({ lat: String(lat), lon: String(lng), format: 'json', addressdetails: '1' }),
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Photon, the address search of the TREK services, asked before Nominatim.
|
||||
*
|
||||
* It answers the forward search and the reverse lookup for an installation
|
||||
* that holds a key for the TREK services and has not set NOMINATIM_URL: an
|
||||
* operator who runs a geocoder of their own keeps it. Photon has no shared
|
||||
* pool, so without a key it is not asked at all.
|
||||
*
|
||||
* Every miss is null and the caller asks Nominatim instead: a refused key, a
|
||||
* spent allowance, a timeout, an error or an answer that is not Photon's all
|
||||
* read to the traveller as the search they had before. After a few misses in
|
||||
* a row it stops asking for a minute, as the Places client does, so an
|
||||
* installation that cannot reach it does not pay the deadline on every search.
|
||||
*
|
||||
* Never imports MapsService: providers sit below the orchestrator.
|
||||
*/
|
||||
import { readEnv } from '../../../app-config';
|
||||
import { capResponse } from '../../../utils/ssrfGuard';
|
||||
import { servicesConfig } from '../../app-config/tokens';
|
||||
import { logDebug, logWarn } from '../../audit/audit-log.logger';
|
||||
import { serviceIdentitySlot } from '../../service-identity/service-identity.interface';
|
||||
import { photonAnswerSchema, photonLang, type PhotonFeature } from './photon.mapping';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
|
||||
/** Short, because Nominatim still has to fit behind it inside the browser's wait. */
|
||||
const TIMEOUT_MS = 2500;
|
||||
/** Ten hits are a few kB. */
|
||||
const MAX_BYTES = 512_000;
|
||||
const SEARCH_LIMIT = 10;
|
||||
/**
|
||||
* How far the bias reaches. Nominatim is handed a box of a degree around the
|
||||
* point; zoom 10 is Photon's spelling of about that.
|
||||
*/
|
||||
const BIAS_ZOOM = 10;
|
||||
const MISSES_BEFORE_PAUSE = 4;
|
||||
const PAUSE_MS = 60_000;
|
||||
|
||||
interface PhotonSearchOptions {
|
||||
lang?: string;
|
||||
bias?: { lat: number; lng: number };
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class PhotonClient {
|
||||
private misses = 0;
|
||||
private pausedUntil = 0;
|
||||
|
||||
constructor(@Inject(servicesConfig.KEY) private readonly config: ConfigType<typeof servicesConfig>) {}
|
||||
|
||||
/** Places matching the query, best first, or null when Nominatim has to answer. */
|
||||
search(query: string, opts: PhotonSearchOptions = {}): Promise<PhotonFeature[] | null> {
|
||||
const params = new URLSearchParams({ q: query, limit: String(SEARCH_LIMIT), lang: photonLang(opts.lang) });
|
||||
if (opts.bias && Number.isFinite(opts.bias.lat) && Number.isFinite(opts.bias.lng)) {
|
||||
params.set('lat', String(opts.bias.lat));
|
||||
params.set('lon', String(opts.bias.lng));
|
||||
params.set('zoom', String(BIAS_ZOOM));
|
||||
}
|
||||
return this.ask('api', params);
|
||||
}
|
||||
|
||||
/** What lies at a point, nearest first, or null when Nominatim has to answer. */
|
||||
reverse(lat: number, lng: number, lang?: string): Promise<PhotonFeature[] | null> {
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return Promise.resolve(null);
|
||||
const params = new URLSearchParams({ lat: String(lat), lon: String(lng), limit: '1', lang: photonLang(lang) });
|
||||
return this.ask('reverse', params);
|
||||
}
|
||||
|
||||
private async ask(path: 'api' | 'reverse', params: URLSearchParams): Promise<PhotonFeature[] | null> {
|
||||
if (!this.mayAsk()) return null;
|
||||
const url = new URL(`${this.config.photonUrl}/${path}`);
|
||||
url.search = params.toString();
|
||||
const identity = serviceIdentitySlot.get();
|
||||
const headers = identity.headersFor(url);
|
||||
if (!headers.Authorization) return null;
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
headers: { Accept: 'application/json', ...headers },
|
||||
// The key goes to this host alone, never on to wherever it points.
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||
});
|
||||
identity.observe(url, res);
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel();
|
||||
throw new Error(`answered ${res.status}`);
|
||||
}
|
||||
const { features } = photonAnswerSchema.parse(await capResponse(res, MAX_BYTES).json());
|
||||
this.misses = 0;
|
||||
return features;
|
||||
} catch (err) {
|
||||
this.noteMiss(err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Off with the services, beside an operator's own Nominatim, and during the pause. */
|
||||
private mayAsk(): boolean {
|
||||
if (this.config.mode === 'off' || readEnv().integrations.nominatimOwn) return false;
|
||||
return Date.now() >= this.pausedUntil;
|
||||
}
|
||||
|
||||
private noteMiss(err: unknown): void {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
this.misses += 1;
|
||||
if (this.misses < MISSES_BEFORE_PAUSE) {
|
||||
logDebug(`[Photon] ${reason}; asking Nominatim instead`);
|
||||
return;
|
||||
}
|
||||
this.pausedUntil = Date.now() + PAUSE_MS;
|
||||
// One more miss after the pause starts the next one.
|
||||
this.misses = MISSES_BEFORE_PAUSE - 1;
|
||||
logWarn(`[Photon] ${reason}; asking Nominatim alone for a minute`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
/**
|
||||
* Photon's answers in the shape Nominatim gives, so search and reverse read
|
||||
* the same to every caller whichever of the two answered.
|
||||
*
|
||||
* Photon is a GeoJSON service: one feature per hit, the coordinate as
|
||||
* [lon, lat], the OSM type as a letter and the address as flat properties.
|
||||
* Nominatim names the type in full, spells the coordinate as text and carries
|
||||
* the address as one comma-joined line. The OsmClient keeps one mapping from
|
||||
* Nominatim's shape to TREK's place record, and this file feeds it.
|
||||
*/
|
||||
import { toApiLang } from '../maps.helpers';
|
||||
import type { NominatimResult, NominatimReverse } from './osm.client';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/** The languages the TREK services imported names for; anything else gets the names used on the spot. */
|
||||
const PHOTON_LANGS: ReadonlySet<string> = new Set([
|
||||
'ar',
|
||||
'az',
|
||||
'ca',
|
||||
'cs',
|
||||
'de',
|
||||
'el',
|
||||
'en',
|
||||
'es',
|
||||
'et',
|
||||
'fr',
|
||||
'hu',
|
||||
'id',
|
||||
'it',
|
||||
'ja',
|
||||
'ko',
|
||||
'nl',
|
||||
'pl',
|
||||
'pt',
|
||||
'ru',
|
||||
'sk',
|
||||
'sv',
|
||||
'th',
|
||||
'tr',
|
||||
'uk',
|
||||
'vi',
|
||||
'zh',
|
||||
]);
|
||||
|
||||
const OSM_TYPES: Readonly<Record<string, string>> = { N: 'node', W: 'way', R: 'relation' };
|
||||
|
||||
const text = z.string().optional();
|
||||
|
||||
const photonFeatureSchema = z.object({
|
||||
geometry: z.object({ coordinates: z.array(z.number()).min(2) }),
|
||||
properties: z.object({
|
||||
osm_type: text,
|
||||
osm_id: z.number().int().optional(),
|
||||
osm_key: text,
|
||||
osm_value: text,
|
||||
type: text,
|
||||
name: text,
|
||||
housenumber: text,
|
||||
street: text,
|
||||
postcode: text,
|
||||
locality: text,
|
||||
district: text,
|
||||
city: text,
|
||||
county: text,
|
||||
state: text,
|
||||
country: text,
|
||||
countrycode: text,
|
||||
extra: z.record(z.string(), z.unknown()).optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const photonAnswerSchema = z.object({ features: z.array(photonFeatureSchema) });
|
||||
|
||||
export type PhotonFeature = z.infer<typeof photonFeatureSchema>;
|
||||
type PhotonProperties = PhotonFeature['properties'];
|
||||
|
||||
/**
|
||||
* The language Photon is asked in: TREK's code through toApiLang (`br` is
|
||||
* Brazilian Portuguese, `gr` Greek), cut to its base (`pt-BR` to `pt`, `zh-TW`
|
||||
* to `zh`). A language the import has no names for, or none at all, asks for
|
||||
* `default`, the names written on the spot.
|
||||
*/
|
||||
export function photonLang(lang: string | undefined): string {
|
||||
if (!lang?.trim()) return 'default';
|
||||
const base = toApiLang(lang).split('-')[0].toLowerCase();
|
||||
return PHOTON_LANGS.has(base) ? base : 'default';
|
||||
}
|
||||
|
||||
/**
|
||||
* The address line Nominatim calls `display_name`: the place's own name first,
|
||||
* then street, quarter, town, county, region, postcode and country. A part
|
||||
* that repeats one before it is left out, so Berlin reads "Berlin, Germany"
|
||||
* rather than naming the city state twice.
|
||||
*/
|
||||
export function photonDisplayName(p: PhotonProperties): string {
|
||||
const street = [p.street, p.housenumber].filter(Boolean).join(' ');
|
||||
const parts = [p.name, street, p.district ?? p.locality, p.city, p.county, p.state, p.postcode, p.country];
|
||||
const seen = new Set<string>();
|
||||
for (const part of parts) {
|
||||
const value = part?.trim();
|
||||
if (value) seen.add(value);
|
||||
}
|
||||
return [...seen].join(', ');
|
||||
}
|
||||
|
||||
/** A search hit as Nominatim would have answered it, or null for one without an OpenStreetMap id. */
|
||||
export function asNominatimHit(feature: PhotonFeature): NominatimResult | null {
|
||||
const p = feature.properties;
|
||||
const osmType = p.osm_type ? OSM_TYPES[p.osm_type] : undefined;
|
||||
if (!osmType || p.osm_id === undefined) return null;
|
||||
const [lon, lat] = feature.geometry.coordinates;
|
||||
return {
|
||||
osm_type: osmType,
|
||||
osm_id: String(p.osm_id),
|
||||
class: p.osm_key,
|
||||
type: p.osm_value,
|
||||
name: p.name,
|
||||
display_name: photonDisplayName(p),
|
||||
lat: String(lat),
|
||||
lon: String(lon),
|
||||
extratags: stringTags(p.extra),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The point a reverse lookup found, in the fields Nominatim's reverse answer
|
||||
* has. A town itself is its own `city`, and a named place is filed under its
|
||||
* main tag the way Nominatim files it (`tourism` for the Eiffel Tower), so the
|
||||
* readers that look for a sight's name before the road find it here too.
|
||||
*/
|
||||
export function asNominatimReverse(feature: PhotonFeature): NominatimReverse {
|
||||
const p = feature.properties;
|
||||
const address: Record<string, string> = {};
|
||||
const put = (key: string, value: string | undefined): void => {
|
||||
if (value?.trim() && !(key in address)) address[key] = value.trim();
|
||||
};
|
||||
put('road', p.street);
|
||||
put('house_number', p.housenumber);
|
||||
put('postcode', p.postcode);
|
||||
put('suburb', p.district ?? p.locality);
|
||||
put('city', p.type === 'city' ? p.name : p.city);
|
||||
put('county', p.county);
|
||||
put('state', p.state);
|
||||
put('country', p.country);
|
||||
put('country_code', p.countrycode?.toLowerCase());
|
||||
if (p.osm_key && p.type !== 'city') put(p.osm_key, p.name);
|
||||
const displayName = photonDisplayName(p);
|
||||
return { display_name: displayName || undefined, name: p.name, address };
|
||||
}
|
||||
|
||||
/** The extra tags Photon passes through, the text ones only. */
|
||||
function stringTags(extra: Record<string, unknown> | undefined): Record<string, string> | null {
|
||||
if (!extra) return null;
|
||||
const tags: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(extra)) {
|
||||
if (typeof value === 'string') tags[key] = value;
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
Reference in New Issue
Block a user