Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(geomap): name a searched house by its street, not by its number
Elian Doran3208afaf548a
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsxindex 1884d3c417..cb1c57c899 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx@@ -16,6 +16,7 @@ import Icon from "../../react/Icon";import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";import { DEFAULT_GEOCODING_PROVIDER_NAME, DEFAULT_PLACE_ICON, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";import { ParentMap } from "./map";+import { describePlace } from "./place_address";import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";/** Shorter queries are not searched. */@@ -232,7 +233,7 @@ export default function SearchBox({ notes, onPickPlace }: SearchBoxProps) {// A place reads over two lines: what it is called, and the address that places it. Every// other row is one thing said once.- const address = entry.kind === "place" ? addressOf(entry.label, entry.result.name) : null;+ const address = entry.kind === "place" ? describePlace(entry.result) : null;return (<span className={`geo-search-entry geo-search-entry-${entry.kind}`}>@@ -320,16 +321,6 @@ function viewportOf(map: MapLibreGLMap): GeoBounds {return [ [ bounds.getWest(), bounds.getSouth() ], [ bounds.getEast(), bounds.getNorth() ] ];}-/**- * What a label says beyond the place's own name, which is the address around it — "Ōta, Japan" of- * "Tokyo, Ōta, Japan". A label that does not begin with the name is left whole, having nothing to- * repeat.- */-function addressOf(label: string, name: string) {- const rest = label.startsWith(name) ? label.slice(name.length) : label;- return rest.replace(/^[\s,]+/, "");-}-/** The notes on the map whose title contains the query and that are drawn somewhere. */function matchMarkers(notes: FNote[], query: string): SearchEntry[] {const needle = query.toLowerCase();diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.tsindex 30e78cc000..298fac6608 100644--- a/apps/client/src/widgets/collections/geomap/geocoding.ts+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts@@ -1,4 +1,5 @@import { nominatim } from "./nominatim";+import type { PlaceAddress } from "./place_address";/*** How much ground counts as here: what a search treats as the area around the reader, and what a@@ -42,6 +43,11 @@ export interface GeoSearchResult {icon?: string;lat: number;lng: number;+ /**+ * Where the place stands, in parts, for naming it and for saying where it is without reciting the+ * whole label. Absent where the provider breaks an address into nothing.+ */+ address?: PlaceAddress;/*** What the place covers, where the geocoder says. A street and the city around it are told apart* by their extent rather than by one zoom level guessed for both.diff --git a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.tsindex 58ccccb866..a8f938b64b 100644--- a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts@@ -96,17 +96,43 @@ describe("Nominatim geocoding", () => {id: "R62422", label: "Berlin, Germany", name: "Berlin", lat: 52.5170365, lng: 13.3888599,// Written south-north-west-east by Nominatim, and read as MapLibre frames one.bounds: [ [ 13.088345, 52.3382448 ], [ 13.7611609, 52.6755087 ] ],- icon: undefined, outline: expect.any(Function)+ icon: undefined, address: undefined, outline: expect.any(Function)},// Named by the leading part of its label, Nominatim having named it nothing itself, and// framed by nothing: its extent is unreadable, and a node has no boundary to fetch.{id: "N17807753", label: "Paris, France", name: "Paris", lat: 48.8566, lng: 2.3522,- bounds: undefined, icon: undefined, outline: undefined+ bounds: undefined, icon: undefined, address: undefined, outline: undefined}]);});+ it("names a house by its street and number, which is what it has instead of a name", async () => {+ // As Nominatim answers for a plain address: no name of its own, and a label led by the number.+ respondWith([ place({+ name: "", osm_type: "way", osm_id: 90,+ display_name: "25, Lankwitzer Straße, Mariendorf, Berlin, 12107, Deutschland",+ address: {+ house_number: "25", road: "Lankwitzer Straße", suburb: "Mariendorf",+ city: "Berlin", state: "Berlin", postcode: "12107",+ country: "Deutschland", country_code: "DE"+ }+ }) ]);++ const [ house ] = await search("lankwitzer strasse 25");+ expect(house.name).toBe("Lankwitzer Straße 25");+ expect(house.address).toEqual({+ street: "Lankwitzer Straße 25", locality: "Berlin", region: "Berlin",+ country: "Deutschland", countryCode: "de"+ });+ });++ it("asks for the address in parts", async () => {+ const fetchMock = respondWith([]);+ await search("berlin");+ expect(requestedUrl(fetchMock).searchParams.get("addressdetails")).toBe("1");+ });+it("carries the kind of place through, for the icon it is drawn with", async () => {respondWith([place({ category: "shop", type: "supermarket", addresstype: "shop" }),diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.tsindex 31bc8ef7c6..4b64aa371f 100644--- a/apps/client/src/widgets/collections/geomap/nominatim.ts+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts@@ -1,6 +1,7 @@import { getCurrentLanguage } from "../../../services/i18n";import { type GeoBounds, type GeocodingProvider, type GeoSearchOptions, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";import { placeIcon } from "./osm_icons";+import { formatStreet, type PlaceAddress } from "./place_address";const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";const NOMINATIM_LOOKUP_URL = "https://nominatim.openstreetmap.org/lookup";@@ -105,6 +106,8 @@ async function searchPlaces(query: string, extraParams: Record<string, string>):q: query,format: "jsonv2",limit: String(MAX_RESULTS),+ // The address in parts, which is what names a house and places a shop (see place_address).+ addressdetails: "1",...extraParams});@@ -142,6 +145,30 @@ interface NominatimPlace {type?: string;/** What kind of address the place is: `city`, `country`, `road`, `shop`. */addresstype?: string;+ /** The address in parts, asked for with `addressdetails`. */+ address?: NominatimAddress;+}++/**+ * Nominatim's breakdown of an address, narrowed to the parts a result is named and placed by.+ *+ * It names the town by what kind of settlement it is, so a place in a village carries `village` and+ * no `city`; the same goes for the region around it (see toAddress).+ */+interface NominatimAddress {+ house_number?: string;+ road?: string;+ city?: string;+ town?: string;+ village?: string;+ hamlet?: string;+ municipality?: string;+ county?: string;+ state?: string;+ province?: string;+ region?: string;+ country?: string;+ country_code?: string;}/** A place as the app holds one, or `null` where the entry carries no readable position. */@@ -152,6 +179,7 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {return null;}+ const address = toAddress(place.address);const prefix = OSM_TYPE_PREFIX[place.osm_type ?? ""];const osmId = prefix && place.osm_id ? `${prefix}${place.osm_id}` : null;const hasBoundary = OSM_TYPES_WITH_A_BOUNDARY.has(place.osm_type ?? "");@@ -163,9 +191,11 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {// back under two of them and is offered twice.id: osmId ?? String(place.place_id ?? `${lat},${lng}`),label: place.display_name,- // Nominatim leaves `name` empty for a result that is an address rather than a named place,- // where the leading part of the label is what names it.- name: place.name || place.display_name.split(",")[0].trim(),+ // Nominatim leaves `name` empty for a result that is an address rather than a named place.+ // Its street and number name it; the leading part of the label, which is the house number on+ // its own, is what is left when even those are missing.+ name: place.name || address?.street || place.display_name.split(",")[0].trim(),+ address,lat,lng,bounds,@@ -174,6 +204,30 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {};}+/**+ * Nominatim's address, in the parts a result is named and placed by, or nothing where it broke the+ * address into none.+ *+ * The town and the region are each named by whichever kind of place fills that role here: a village+ * has no `city`, and a county stands in for a state where a country has no states.+ */+function toAddress(address: NominatimAddress | undefined): PlaceAddress | undefined {+ if (!address) {+ return undefined;+ }++ const countryCode = address.country_code?.toLowerCase();+ const place: PlaceAddress = {+ street: formatStreet(address.house_number, address.road, countryCode),+ locality: address.city ?? address.town ?? address.village ?? address.hamlet ?? address.municipality,+ region: address.state ?? address.province ?? address.region ?? address.county,+ country: address.country,+ countryCode+ };++ return Object.values(place).some(Boolean) ? place : undefined;+}+/** The extent Nominatim reports, as MapLibre reads one, or nothing where it cannot be read. */function toBounds(boundingbox: string[] | undefined): GeoSearchResult["bounds"] {if (boundingbox?.length !== 4) {diff --git a/apps/client/src/widgets/collections/geomap/place_address.spec.ts b/apps/client/src/widgets/collections/geomap/place_address.spec.tsnew file mode 100644index 0000000000..7b29f5aa32--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/place_address.spec.ts@@ -0,0 +1,53 @@+/** An address held in parts: how a street is written, and how few parts place a result. */+import { describe, expect, it } from "vitest";++import { describePlace, formatStreet } from "./place_address";++describe("Place addresses", () => {+ it("writes the number on the side of the street the country writes it", () => {+ expect(formatStreet("25", "Lankwitzer Straße", "de")).toBe("Lankwitzer Straße 25");+ expect(formatStreet("28", "Strada Memorandumului", "ro")).toBe("Strada Memorandumului 28");+ expect(formatStreet("1600", "Pennsylvania Avenue", "us")).toBe("1600 Pennsylvania Avenue");+ expect(formatStreet("10", "Downing Street", "gb")).toBe("10 Downing Street");++ // A country not named reads the way most of the world writes an address.+ expect(formatStreet("7", "Šeříková", "cz")).toBe("Šeříková 7");+ expect(formatStreet("7", "Šeříková", undefined)).toBe("Šeříková 7");+ });++ it("has nothing to write without a road, and writes the road alone without a number", () => {+ expect(formatStreet("25", undefined, "de")).toBeUndefined();+ expect(formatStreet(undefined, "Lankwitzer Straße", "de")).toBe("Lankwitzer Straße");+ });++ it("places a result by its street and its town, leaving out what places nothing", () => {+ // The postcode and the boroughs between are never among the parts.+ expect(describePlace({+ name: "REWE",+ label: "REWE, 19-24, Lankwitzer Straße, Lichterfelde, Steglitz-Zehlendorf, Berlin, 12209, Deutschland",+ address: {+ street: "Lankwitzer Straße 19-24", locality: "Berlin", region: "Berlin",+ country: "Deutschland", countryCode: "de"+ }+ })).toBe("Lankwitzer Straße 19-24, Berlin, Deutschland");+ });++ it("does not place a city inside itself", () => {+ expect(describePlace({+ name: "Berlin",+ label: "Berlin, Deutschland",+ address: { locality: "Berlin", region: "Berlin", country: "Deutschland", countryCode: "de" }+ })).toBe("Deutschland");++ // A country is placed by nothing: it is the last part there is, and it is its own name.+ expect(describePlace({+ name: "Deutschland", label: "Deutschland",+ address: { country: "Deutschland", countryCode: "de" }+ })).toBe("");+ });++ it("falls back on the label where a provider breaks an address into no parts", () => {+ expect(describePlace({ name: "Tokyo", label: "Tokyo, Ōta, Japan" })).toBe("Ōta, Japan");+ expect(describePlace({ name: "Nowhere", label: "Somewhere else" })).toBe("Somewhere else");+ });+});diff --git a/apps/client/src/widgets/collections/geomap/place_address.ts b/apps/client/src/widgets/collections/geomap/place_address.tsnew file mode 100644index 0000000000..57dd0e8d7b--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/place_address.ts@@ -0,0 +1,81 @@+/**+ * A place's address broken into the parts worth showing, and how those parts are put back together.+ *+ * A geocoder answers with the whole address written out — house number, street, quarter, borough,+ * city, postcode, country — which is more than a row of a result list can hold and more than a reader+ * needs to tell two places apart. Held in parts, the address can be named by its street and placed by+ * its town without the postcode and the boroughs in between.+ *+ * The parts themselves are what any geocoder reports, under whatever keys it uses; mapping its keys+ * onto these is the provider's own work (see nominatim.ts).+ */++/** A place's address, in the parts a result is named and placed by. */+export interface PlaceAddress {+ /** The street and its number, in the order the country writes them (see {@link formatStreet}). */+ street?: string;+ /** The town the place stands in: a city, a town, a village, or the nearest thing to one. */+ locality?: string;+ /** The state, province or county around that town, which is what tells two towns of one name apart. */+ region?: string;+ /** The country's name, in the language the search was made in. */+ country?: string;+ /** The country's ISO 3166-1 alpha-2 code, lowercased — `de`, `ro`, `us`. */+ countryCode?: string;+}++/**+ * The street line of an address: a road and the number on it, or nothing where there is no road.+ *+ * Which side the number goes is a matter of where the place is rather than of what language the app+ * runs in — a Berlin address reads `Lankwitzer Straße 25` to every reader there is. Most of the world+ * writes the number after the street, so that is what a country not named below gets.+ */+export function formatStreet(houseNumber: string | undefined, road: string | undefined, countryCode?: string) {+ if (!road) {+ return undefined;+ }+ if (!houseNumber) {+ return road;+ }++ return NUMBER_BEFORE_STREET.has(countryCode ?? "")+ ? `${houseNumber} ${road}`+ : `${road} ${houseNumber}`;+}++/**+ * Where a place stands, said in as few parts as tell it from another of the same name.+ *+ * The street, the town, the region around it and the country — dropping the postcode and the quarters+ * and boroughs between them, which place nothing for a reader. A part that repeats what the place is+ * already called is dropped as well, so a city named `Berlin` is placed in `Deutschland` rather than+ * in `Berlin, Berlin, Deutschland`.+ *+ * The whole label, less the name at the front of it, for a provider that reports no parts at all.+ */+export function describePlace({ name, label, address }: { name: string; label: string; address?: PlaceAddress }) {+ if (!address) {+ const rest = label.startsWith(name) ? label.slice(name.length) : label;+ return rest.replace(/^[\s,]+/, "");+ }++ const parts: string[] = [];+ for (const part of [ address.street, address.locality, address.region, address.country ]) {+ if (part && part !== name && part !== parts[parts.length - 1]) {+ parts.push(part);+ }+ }++ return parts.join(", ");+}++/**+ * The countries that write the number before the street.+ *+ * Kept to the ones whose convention is not in doubt; a country left out reads the other way round,+ * which is what most of the world does and what a wrong guess should fall back on.+ */+const NUMBER_BEFORE_STREET = new Set([+ "au", "ca", "fr", "gb", "hk", "ie", "in", "my", "nz", "ph", "sg", "th", "us", "za"+]);