feat(atlas): search by place, and count cities that are actually cities (#1908)

* refactor(atlas): drop the last-trip tile from the stats bar

The row beside the continent counts is statistics; a single trip sitting in it
was neither, and the trip it named is already one click away in the country
detail below. Its two locale keys go with it, along with atlas.lastVisitLabel,
which nothing had rendered for a while.

* feat(atlas): resolve a coordinate to its country and region

Groundwork for searching the atlas by place: /locate answers with the admin1
region a point falls in, resolved against the same bundled polygons the visited
colouring uses, so the answer is always something the map can highlight. A
country without admin1 coverage resolves to a country and a null region, which
is a real answer rather than a failure.

* feat(atlas): search the map by place, not only by country

Typing a city geocodes it through the same /maps/search everything else uses and
offers the hits below the instant local country matches. Picking one flies there
and opens the dialog for the region it sits in, so Milan marks Lombardy without
the user knowing that is where Milan is.

The country list stays offline and instant; only the place lookup waits on the
network, debounced and sequence-guarded so a slow answer cannot overwrite a
newer query.

* fix(atlas): count cities instead of shop names

The visited-cities figure scanned the address left to right and took the first
part that was not a country and matched a latin-only pattern. The first part of
a geocoded address is the place itself, so a trip to Tokyo counted Shibuya Sky,
Shibuya Parco and Family Mart as three cities, while an address written in
Japanese, Cyrillic, Greek or Korean counted none at all.

Read from the administrative end instead, skipping the country, anything with
digits, and the region already resolved for that place in place_regions, which
is what separates the city from the region above it. On one real trip the count
went from 20 entries, nearly all of them streets and shops, to Paris, Shibuya,
Minato and three Berlin boroughs.

* i18n(atlas): translate the place-search heading

* docs(atlas): document place search and how cities are counted

* fix(atlas): stop the search panel closing itself while results arrive

The dropdown closed on mouseleave, which was survivable while it held only local
country matches and appeared complete in one go. Geocoded places land a moment
later and grow the list under a cursor already resting there, so the panel shut
itself seconds after opening. Closes on a click outside now, Escape unchanged.
This commit is contained in:
Maurice
2026-08-12 14:14:37 +02:00
committed by GitHub
parent 6e10ffa75d
commit 767dc662b7
38 changed files with 531 additions and 102 deletions
+19 -1
View File
@@ -14,7 +14,7 @@ import {
UseGuards,
} from '@nestjs/common';
import type { Response } from 'express';
import type { RegionGeo } from '@trek/shared';
import type { AtlasLocateResponse, RegionGeo } from '@trek/shared';
import type { User } from '../../types';
import { AtlasService } from './atlas.service';
import { AtlasMarkRegionDto, AtlasCreateBucketItemDto, AtlasUpdateBucketItemDto } from './atlas.dto';
@@ -51,6 +51,24 @@ export class AtlasController {
return this.atlas.visitedRegions(user.id);
}
/**
* Which country and admin1 region a coordinate falls in (#1115). The Atlas search
* used to know country names only, so finding Milan meant knowing it is in Lombardy
* first. The client geocodes the term through /maps/search as everywhere else and
* sends the winning coordinate here; resolution runs against the same bundled
* polygons the visited-region colouring uses, so the answer is always a feature the
* map can actually highlight.
*/
@Get('locate')
async locate(@Query('lat') lat: string, @Query('lng') lng: string): Promise<AtlasLocateResponse> {
const latNum = Number(lat);
const lngNum = Number(lng);
if (!Number.isFinite(latNum) || !Number.isFinite(lngNum) || Math.abs(latNum) > 90 || Math.abs(lngNum) > 180) {
throw new HttpException({ error: 'Valid lat and lng are required' }, 400);
}
return this.atlas.locate(latNum, lngNum);
}
@Get('regions/geo')
async regionGeo(
@Query('countries') countries: string | undefined,
+30 -7
View File
@@ -1,16 +1,19 @@
import { Injectable } from '@nestjs/common';
import { CONTINENT_MAP, strongerVisitStatus, todayUtc, tripVisitStatus, VisitStatus } from '@trek/shared';
import type { AtlasLocateResponse } from '@trek/shared';
import { Trip, Place } from '../../types';
import { DatabaseService } from '../database/database.service';
import {
getCountryFromCoords,
getCountryGeoGz,
getRegionFromCoords,
getRegionGeo,
geocodingInFlight,
resolveCountryCodeSync,
reverseGeocodeRegion,
} from './atlas-geo';
import { KNOWN_COUNTRIES } from './known-countries';
import { cityFromAddress } from './city-from-address';
import { haversineKm } from '../common/geo';
export type CreateBucketData = {
@@ -705,6 +708,26 @@ export class AtlasService {
// ── Region GeoJSON / country geometry (delegates to the atlas-geo module) ──
/**
* Resolve a coordinate to the country and admin1 region the map draws (#1115), so
* searching for a city can highlight the region it sits in without the user knowing
* which one that is. Reads the same bundled polygons as the visited-region colouring,
* so the answer is always a feature the client can highlight. A country with no admin1
* coverage in the bundle resolves to a country and a null region, which is a real
* answer rather than a failure: zooming to the country is still what the user wanted.
*/
async locate(lat: number, lng: number): Promise<AtlasLocateResponse> {
const countryCode = getCountryFromCoords(lat, lng);
if (!countryCode) return { country_code: null, region_code: null, region_name: null };
const region = await getRegionFromCoords(countryCode, lat, lng);
return {
country_code: countryCode.toUpperCase(),
region_code: region?.region_code ?? null,
region_name: region?.region_name ?? null,
};
}
regionGeo(countries: string[]) {
return getRegionGeo(countries);
}
@@ -796,11 +819,14 @@ export class AtlasService {
// ---------------------------------------------------------------------------
getTravelStats(userId: number) {
const places = this.db.all<{ address: string | null; lat: number | null; lng: number | null }>(`
SELECT DISTINCT p.address, p.lat, p.lng
// The resolved region rides along so cityFromAddress can tell the city apart from
// the region sitting right above it in the same address (#1115).
const places = this.db.all<{ address: string | null; lat: number | null; lng: number | null; region_name: string | null }>(`
SELECT DISTINCT p.address, p.lat, p.lng, pr.region_name
FROM places p
JOIN trips t ON p.trip_id = t.id
LEFT JOIN trip_members tm ON t.id = tm.trip_id
LEFT JOIN place_regions pr ON pr.place_id = p.id
WHERE t.user_id = ? OR tm.user_id = ?
`, userId, userId);
@@ -823,11 +849,8 @@ export class AtlasService {
// Explicit null checks: lat/lng of exactly 0 (equator / prime meridian)
// are valid coordinates the former falsy check silently dropped.
if (p.lat != null && p.lng != null) coords.push({ lat: p.lat, lng: p.lng });
if (p.address) {
const parts = p.address.split(',').map(s => s.trim().replace(/\d{3,}/g, '').trim());
const cityPart = parts.find(s => !KNOWN_COUNTRIES.has(s) && /^[A-Za-z\u00C0-\u00FF\s-]{2,}$/.test(s));
if (cityPart) cities.add(cityPart);
}
const cityPart = cityFromAddress(p.address, part => KNOWN_COUNTRIES.has(part), p.region_name);
if (cityPart) cities.add(cityPart);
});
// Visited countries \u2014 same source the Atlas page uses: ISO-2 codes from
@@ -0,0 +1,62 @@
/**
* Pull the settlement out of a formatted address, for the "cities visited" figure.
*
* The previous version scanned the parts left to right and took the first one that
* was not a known country and matched a latin-only pattern. Both halves were wrong.
* Left to right means the first part, which in a geocoder's output is the name of the
* place itself, so "Shibuya Sky, 12, Shibuya 2, Shibuya, Tokyo, 150-0002, Japan"
* counted "Shibuya Sky" as a city, and the pattern excluded every non-latin script,
* so an address written in Japanese, Cyrillic, Greek or Korean counted nothing at all.
*
* Reading from the end instead lands on the administrative tail, where the settlement
* lives. The trick for separating the city from the region above it is that we already
* know the region: `place_regions.region_name` is filled by the geocoder, so it can
* simply be skipped. For the address above, with the region resolved as Tokyo, walking
* back past Japan (country), 150-0002 (digits) and Tokyo (the region) lands on Shibuya.
*
* This is still a heuristic over a formatted string. Structured `address.city` from the
* geocoder would be exact, but the fast path for region resolution runs against bundled
* polygons and never calls the geocoder at all, so storing a city would mean an extra
* network round trip per place. Not worth it for one number on a stats card.
*/
/** A part carrying digits is a postcode, a house number or a numbered district. */
function hasDigits(part: string): boolean {
return /\d/.test(part);
}
function normalize(value: string): string {
return value.trim().toLowerCase();
}
export function cityFromAddress(
address: string | null | undefined,
isKnownCountry: (part: string) => boolean,
regionName?: string | null,
): string | null {
if (!address) return null;
const parts = address.split(',').map(p => p.trim()).filter(Boolean);
// One part is the place's own name, never an address with a city in it.
if (parts.length < 2) return null;
const region = regionName ? normalize(regionName) : null;
// A geocoder always ends on the country, so drop the last part outright once the
// address is long enough for that to be certain. The country-name list below still
// runs for every part, but it is a finite list (it has no "Nederland", for one), and
// this way a country it has never heard of cannot be counted as a city.
const last = parts.length >= 3 ? parts.length - 2 : parts.length - 1;
// Index 0 stays out of the running: geocoders lead with the place itself.
for (let i = last; i >= 1; i--) {
const part = parts[i];
if (hasDigits(part)) continue;
if (isKnownCountry(part)) continue;
if (region && normalize(part) === region) continue;
// Anything with no letter at all (stray punctuation, a lone dash) is not a name.
if (!/\p{L}/u.test(part)) continue;
return part;
}
return null;
}
+4
View File
@@ -7,6 +7,10 @@
* into places.address, which is display text in the user's language.
*/
export const KNOWN_COUNTRIES = new Set([
// Nominatim inserts an extra tier above the country for France and its overseas
// territories, which reads exactly like a place name and would otherwise be counted
// as a city.
'Metropolitanes Frankreich', 'France métropolitaine', 'Metropolitan France',
'Japan', 'Germany', 'Deutschland', 'France', 'Frankreich', 'Italy', 'Italien', 'Spain', 'Spanien',
'United States', 'USA', 'United Kingdom', 'UK', 'Thailand', 'Australia', 'Australien',
'Canada', 'Kanada', 'Mexico', 'Mexiko', 'Brazil', 'Brasilien', 'China', 'India', 'Indien',