Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): draw the boundary of a searched place that covers ground

Elian Dorana56c2ea1ee43
diff --git a/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx b/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx
index c47f553419..7b99f19ec4 100644
--- a/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/PlaceMarker.spec.tsx
@@ -10,7 +10,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { MapStyleLoaded, ParentMap } from "./map";
import { LABEL_PAINT, MARKER_SHADOW_PADDING, markerImageId } from "./Markers";
-import PlaceMarker, { PLACE_LAYER, PLACE_MARKER_COLOR, PLACE_MARKER_ICON, PLACE_SOURCE } from "./PlaceMarker";
+import PlaceMarker, { OUTLINE_FILL_LAYER, OUTLINE_LINE_LAYER, OUTLINE_SOURCE, PLACE_LAYER, PLACE_MARKER_COLOR, PLACE_MARKER_ICON, PLACE_SOURCE } from "./PlaceMarker";
// The pin is rasterized by loading an SVG into an Image, and happy-dom never fires that load — so
// the layer, which waits for the pin, would never be added. Only the rasterizing is stood in for;
@@ -22,6 +22,12 @@ vi.mock("./Markers", async (importOriginal) => ({
const TOKYO: [number, number] = [ 139.6503, 35.6762 ];
+/** The ground a place covers, as a geocoder reports the boundary of a country or a county. */
+const OUTLINE: GeoJSON.Geometry = {
+ type: "Polygon",
+ coordinates: [ [ [ 139.5, 35.5 ], [ 139.9, 35.5 ], [ 139.9, 35.8 ], [ 139.5, 35.8 ], [ 139.5, 35.5 ] ] ]
+};
+
interface FakeLayer {
id: string;
source?: string;
@@ -29,21 +35,33 @@ interface FakeLayer {
paint?: Record<string, unknown>;
}
+/** A layer as it was added: what it was, and which layer it was asked to go under. */
+interface AddedLayer {
+ layer: FakeLayer;
+ beforeId?: string;
+}
+
/** A map that records what the component adds to it and takes away again. */
function fakeMap() {
const layers = new Map<string, FakeLayer>();
const sources = new Map<string, unknown>();
const images = new Set<string>();
const removals: string[] = [];
+ const added: AddedLayer[] = [];
return {
removals,
+ /** Where a layer was asked to be placed, which is what settles what is drawn over what. */
+ addedBefore: (id: string) => added.find((entry) => entry.layer.id === id)?.beforeId,
layer: (id: string) => layers.get(id),
source: (id: string) => sources.get(id),
hasImage: (id: string) => images.has(id),
addImage: (id: string) => { images.add(id); },
addSource: (id: string, source: unknown) => { sources.set(id, source); },
- addLayer: (layer: FakeLayer) => { layers.set(layer.id, layer); },
+ addLayer: (layer: FakeLayer, beforeId?: string) => {
+ layers.set(layer.id, layer);
+ added.push({ layer, beforeId });
+ },
getSource: (id: string) => sources.get(id),
getLayer: (id: string) => layers.get(id),
removeSource: (id: string) => { removals.push(`source:${id}`); sources.delete(id); },
@@ -56,24 +74,34 @@ function fakeMap() {
const containers: HTMLElement[] = [];
/** Puts the pin on a map whose style is ready, and settles the pin image the layer waits for. */
-async function renderMarker(map: ReturnType<typeof fakeMap>, { name = "Tokyo", isDarkTheme = false } = {}) {
+async function renderMarker(map: ReturnType<typeof fakeMap>, props: {
+ name?: string; isDarkTheme?: boolean; outline?: GeoJSON.Geometry;
+} = {}) {
const container = document.createElement("div");
document.body.appendChild(container);
containers.push(container);
- await act(async () => {
- render(
- <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
- <MapStyleLoaded.Provider value={true}>
- <PlaceMarker center={TOKYO} name={name} isDarkTheme={isDarkTheme} />
- </MapStyleLoaded.Provider>
- </ParentMap.Provider>,
- container
- );
- });
- await settle();
+ async function draw({ name = "Tokyo", isDarkTheme = false, outline }: typeof props) {
+ await act(async () => {
+ render(
+ <ParentMap.Provider value={map as unknown as MapLibreGLMap}>
+ <MapStyleLoaded.Provider value={true}>
+ <PlaceMarker center={TOKYO} name={name} isDarkTheme={isDarkTheme} outline={outline} />
+ </MapStyleLoaded.Provider>
+ </ParentMap.Provider>,
+ container
+ );
+ });
+ await settle();
+ }
+
+ await draw(props);
- return { unmount: async () => { await act(async () => { render(null, container); }); } };
+ return {
+ /** The same pin drawn again with something changed — a boundary having arrived, say. */
+ rerender: (changed: typeof props) => draw({ ...props, ...changed }),
+ unmount: async () => { await act(async () => { render(null, container); }); }
+ };
}
/** Lets the awaited pin image arrive, which is what the layer is held back for. */
@@ -129,6 +157,31 @@ describe("geo map PlaceMarker", () => {
expect(dark.layer(PLACE_LAYER)?.paint).toMatchObject(LABEL_PAINT.dark);
});
+ it("draws the ground a place covers under its pin, where it covers any", async () => {
+ const map = fakeMap();
+
+ // The boundary is fetched once a place has been picked, so it arrives after the pin is up.
+ const { rerender } = await renderMarker(map);
+ await rerender({ outline: OUTLINE });
+
+ expect(map.source(OUTLINE_SOURCE)).toMatchObject({ type: "geojson", data: { geometry: OUTLINE } });
+ // A tint the map still shows through, ringed by the same colour the pin is drawn in.
+ expect(map.layer(OUTLINE_FILL_LAYER)?.paint).toMatchObject({ "fill-color": PLACE_MARKER_COLOR });
+ expect(map.layer(OUTLINE_LINE_LAYER)?.paint).toMatchObject({ "line-color": PLACE_MARKER_COLOR });
+ // Under the pin, which would otherwise be buried by its own boundary.
+ expect(map.addedBefore(OUTLINE_FILL_LAYER)).toBe(PLACE_LAYER);
+ expect(map.addedBefore(OUTLINE_LINE_LAYER)).toBe(PLACE_LAYER);
+ });
+
+ it("draws no boundary for a place that stands at a point", async () => {
+ const map = fakeMap();
+
+ await renderMarker(map);
+
+ expect(map.layer(OUTLINE_FILL_LAYER)).toBeUndefined();
+ expect(map.source(OUTLINE_SOURCE)).toBeUndefined();
+ });
+
it("takes the layer and its source away with it, the layer first", async () => {
const map = fakeMap();
const { unmount } = await renderMarker(map);
@@ -139,4 +192,16 @@ describe("geo map PlaceMarker", () => {
// A source still drawn from cannot be removed, so the layer goes first.
expect(map.removals).toEqual([ `layer:${PLACE_LAYER}`, `source:${PLACE_SOURCE}` ]);
});
+
+ it("takes the boundary away with it too", async () => {
+ const map = fakeMap();
+ const { unmount } = await renderMarker(map, { outline: OUTLINE });
+
+ await unmount();
+
+ expect(map.removals).toEqual([
+ `layer:${PLACE_LAYER}`, `source:${PLACE_SOURCE}`,
+ `layer:${OUTLINE_FILL_LAYER}`, `layer:${OUTLINE_LINE_LAYER}`, `source:${OUTLINE_SOURCE}`
+ ]);
+ });
});
diff --git a/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
index fff1459d9b..ba3850e05d 100644
--- a/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
+++ b/apps/client/src/widgets/collections/geomap/PlaceMarker.tsx
@@ -12,6 +12,13 @@ export const PLACE_MARKER_ICON = "bx bx-search";
export const PLACE_SOURCE = "searched-place";
export const PLACE_LAYER = "searched-place-layer";
+export const OUTLINE_SOURCE = "searched-place-outline";
+export const OUTLINE_FILL_LAYER = "searched-place-outline-fill";
+export const OUTLINE_LINE_LAYER = "searched-place-outline-line";
+
+/** How much of the map shows through the boundary's fill, which is a tint rather than a covering. */
+const OUTLINE_FILL_OPACITY = 0.12;
+
interface PlaceMarkerProps {
/** Where the place stands, as `[lng, lat]`. */
center: [number, number];
@@ -19,6 +26,8 @@ interface PlaceMarkerProps {
name: string;
/** Whether the map's style is a dark one, which decides how the label is drawn (see Markers). */
isDarkTheme: boolean;
+ /** The ground the place covers, for one that is an area rather than a point. */
+ outline?: GeoJSON.Geometry;
}
/**
@@ -29,8 +38,11 @@ interface PlaceMarkerProps {
* rasterizer and the same label layout and paint the note markers use (see Markers), so it is drawn
* as a marker of the map rather than as something laid over it — the name included, which follows
* the style from light to dark as every other label on the map does.
+ *
+ * A place that covers ground rather than standing at a point — a country, a county — also has that
+ * ground drawn under the pin, in the pin's own colour so the two read as one answer.
*/
-export default function PlaceMarker({ center, name, isDarkTheme }: PlaceMarkerProps) {
+export default function PlaceMarker({ center, name, isDarkTheme, outline }: PlaceMarkerProps) {
const parentMap = useContext(ParentMap);
const styleLoaded = useContext(MapStyleLoaded);
@@ -124,5 +136,73 @@ export default function PlaceMarker({ center, name, isDarkTheme }: PlaceMarkerPr
};
}, [ parentMap, styleLoaded, center, name, isDarkTheme ]);
+ useEffect(() => {
+ if (!parentMap || !outline) return;
+ // Aliased so the narrowing above carries into the nested function below.
+ const map = parentMap;
+ const geometry = outline;
+
+ function addOutline() {
+ try {
+ if (map.getLayer(OUTLINE_FILL_LAYER)) return;
+
+ map.addSource(OUTLINE_SOURCE, {
+ type: "geojson",
+ data: { type: "Feature", geometry, properties: {} }
+ });
+
+ // Under the pin, which would otherwise be buried by the boundary drawn around it.
+ // The pin's layer is only there once its image has been rasterized, so where it is
+ // not yet, the boundary goes on top and the pin is added above it in its turn.
+ const beforeId = map.getLayer(PLACE_LAYER) ? PLACE_LAYER : undefined;
+
+ map.addLayer({
+ id: OUTLINE_FILL_LAYER,
+ type: "fill",
+ source: OUTLINE_SOURCE,
+ paint: {
+ "fill-color": PLACE_MARKER_COLOR,
+ "fill-opacity": OUTLINE_FILL_OPACITY
+ }
+ }, beforeId);
+
+ map.addLayer({
+ id: OUTLINE_LINE_LAYER,
+ type: "line",
+ source: OUTLINE_SOURCE,
+ paint: {
+ "line-color": PLACE_MARKER_COLOR,
+ "line-width": 2
+ }
+ }, beforeId);
+ } catch (e) {
+ if (styleLoaded) {
+ console.warn("Geo map: could not draw the searched place's boundary —", e);
+ }
+ }
+ }
+
+ if (styleLoaded) {
+ addOutline();
+ }
+ map.on("style.load", addOutline);
+
+ return () => {
+ map.off("style.load", addOutline);
+ try {
+ for (const layer of [ OUTLINE_FILL_LAYER, OUTLINE_LINE_LAYER ]) {
+ if (map.getLayer(layer)) {
+ map.removeLayer(layer);
+ }
+ }
+ if (map.getSource(OUTLINE_SOURCE)) {
+ map.removeSource(OUTLINE_SOURCE);
+ }
+ } catch {
+ // The map may already have been removed.
+ }
+ };
+ }, [ parentMap, styleLoaded, outline ]);
+
return null;
}
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index 354e354169..f7068f8f2d 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -17,8 +17,8 @@ import SearchBox from "./SearchBox";
/** The pin is drawn on the map by its own component, which has a spec of its own; here it only has to
* stand in the right place, so it is rendered as something the DOM can be asked about. */
vi.mock("./PlaceMarker", () => ({
- default: ({ center, name }: { center: [number, number]; name: string }) =>
- <div className="place-marker" data-center={center.join(",")} data-name={name} />
+ default: ({ center, name, outline }: { center: [number, number]; name: string; outline?: GeoJSON.Geometry }) =>
+ <div className="place-marker" data-center={center.join(",")} data-name={name} data-outline={outline?.type} />
}));
// i18next is not initialized under test, so t() returns "". The key stands in for the text, with any
@@ -248,6 +248,40 @@ describe("geo map SearchBox", () => {
expect(pin()).toBeNull();
});
+ it("asks for a place's boundary only once that place has been picked", async () => {
+ const outline = vi.fn(async () => ({ type: "Polygon", coordinates: [] } as GeoJSON.Geometry));
+ mockGeocoder([ { ...TOKYO, outline } ]);
+ const container = renderSearchBox(fakeMap(), []);
+
+ await type(container, "tokyo");
+ // The row that runs the geocoder, which offers the place but does not settle on it.
+ await pick(0);
+ expect(outline).not.toHaveBeenCalled();
+
+ await pick(0);
+
+ expect(outline).toHaveBeenCalledOnce();
+ expect(container.querySelector<HTMLElement>(".place-marker")?.dataset.outline).toBe("Polygon");
+ });
+
+ it("drops a boundary that arrives after the place it belongs to has been replaced", async () => {
+ let deliver: ((outline: GeoJSON.Geometry) => void) | undefined;
+ const outline = vi.fn(() => new Promise<GeoJSON.Geometry>((resolve) => { deliver = resolve; }));
+ mockGeocoder([ { ...TOKYO, outline } ]);
+ const container = renderSearchBox(fakeMap(), mapNotes());
+
+ await type(container, "tokyo");
+ await pick(1);
+ await pick(1);
+
+ // A note of the map's own is settled on while the boundary is still being fetched.
+ await type(container, "tokyo trip");
+ await pick(0);
+ await act(async () => { deliver?.({ type: "Polygon", coordinates: [] }); });
+
+ expect(container.querySelector(".place-marker")).toBeNull();
+ });
+
it("takes the pin off the map once the field is emptied", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), []);
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index b2c882112d..c5f6038d44 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -60,7 +60,13 @@ type SearchEntry = {
* A place from the geocoder: `name` is what its pin is labelled with, and `bounds` how much
* ground it covers, where the geocoder says.
*/
- | { kind: "place"; center: [number, number]; name: string; bounds?: GeoSearchResult["bounds"] }
+ | {
+ kind: "place";
+ center: [number, number];
+ name: string;
+ bounds?: GeoSearchResult["bounds"];
+ outline?: GeoSearchResult["outline"];
+ }
/** Runs the geocoder for `query`. */
| { kind: "geocode"; query: string }
/** Reports on a geocoder run; picking it does nothing. */
@@ -98,7 +104,14 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
// `keepOpenOnPick`. Typing again clears it.
const [ dismissed, setDismissed ] = useState(false);
// The geocoder's last answer, pinned where it stands; nothing while the map shows only its notes.
- const [ pickedPlace, setPickedPlace ] = useState<{ center: [number, number]; name: string }>();
+ const [ pickedPlace, setPickedPlace ] = useState<{
+ center: [number, number];
+ name: string;
+ outline?: GeoJSON.Geometry;
+ }>();
+ // Which pick the map currently stands on, so a boundary arriving after a later pick is dropped
+ // rather than drawn around the place that replaced it.
+ const latestPick = useRef(0);
const entriesByKey = useRef(new Map<string, SearchEntry>());
// Discards a run superseded by a later one, since each reports through the same state.
const latestRun = useRef(0);
@@ -121,6 +134,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
setQuery(newQuery);
// Emptying the field is how the pin is taken back off the map.
if (!newQuery.trim()) {
+ latestPick.current++;
setPickedPlace(undefined);
}
}, []);
@@ -147,10 +161,23 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
if (entry.kind === "geocode") {
runGeocoder(entry.query);
} else if (entry.kind === "marker" || entry.kind === "place") {
+ const pickId = ++latestPick.current;
setQuery(entry.label);
setDismissed(true);
// A note already has a marker of its own to fly to; only a place needs one put down.
setPickedPlace(entry.kind === "place" ? { center: entry.center, name: entry.name } : undefined);
+
+ // The ground a country or a county covers, fetched only now that one of the places the
+ // search offered has been settled on. A place that is a point has none, and one whose
+ // boundary cannot be fetched keeps its pin.
+ if (entry.kind === "place" && entry.outline) {
+ entry.outline()
+ .then((outline) => {
+ if (!outline || latestPick.current !== pickId) return;
+ setPickedPlace((current) => current && { ...current, outline });
+ })
+ .catch((e) => logError(`Fetching the boundary of "${entry.label}" failed: ${e}`));
+ }
if (entry.kind === "place" && entry.bounds) {
// Framed by what the place covers rather than flown to at a level guessed for every
// place alike: one zoom that suits a city shows a street as the city around it.
@@ -178,7 +205,10 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
return (
<>
- {pickedPlace && <PlaceMarker center={pickedPlace.center} name={pickedPlace.name} isDarkTheme={isDarkTheme} />}
+ {pickedPlace && <PlaceMarker
+ center={pickedPlace.center} name={pickedPlace.name}
+ outline={pickedPlace.outline} isDarkTheme={isDarkTheme}
+ />}
<OverlayToolbar className="geo-search-toolbar" titlePosition="bottom">
<Icon icon="bx bx-search" className="geo-search-icon" />
<FormAutocomplete
@@ -259,7 +289,8 @@ function placeEntry(result: GeoSearchResult): SearchEntry {
name: result.name,
icon: "bx bx-map-pin",
center: [ result.lng, result.lat ],
- bounds: result.bounds
+ bounds: result.bounds,
+ outline: result.outline
};
}
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.ts
index def28dd194..69d0864e8f 100644
--- a/apps/client/src/widgets/collections/geomap/geocoding.ts
+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts
@@ -16,6 +16,14 @@ export interface GeoSearchResult {
* for both.
*/
bounds?: [[number, number], [number, number]];
+ /**
+ * Fetches the boundary of the place — a country's coastline, a county's border — or `null` where
+ * it has none worth drawing. Absent where the provider cannot supply one at all.
+ *
+ * A call rather than a value, so the boundary is asked for only once a place has been picked: a
+ * search returns several places and at most one of them is ever looked at.
+ */
+ outline?: () => Promise<GeoJSON.Geometry | null>;
}
export interface GeocodingProvider {
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
index 8663a152d3..9d4d02a62d 100644
--- a/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.spec.ts
@@ -13,6 +13,8 @@ function place(overrides: Record<string, unknown> = {}) {
return {
place_id: 240109189,
name: "Berlin",
+ osm_type: "relation",
+ osm_id: 62422,
display_name: "Berlin, Germany",
boundingbox: [ "52.3382448", "52.6755087", "13.0883450", "13.7611609" ],
lat: "52.5170365",
@@ -71,7 +73,7 @@ describe("Nominatim geocoding", () => {
place({ place_id: 3, display_name: undefined }),
place({
place_id: 4, name: undefined, display_name: "Paris, France", lat: "48.8566", lon: "2.3522",
- boundingbox: [ "not", "a", "box", "at all" ]
+ boundingbox: [ "not", "a", "box", "at all" ], osm_type: "node", osm_id: 17807753
})
]);
@@ -79,11 +81,15 @@ describe("Nominatim geocoding", () => {
{
id: "240109189", 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 ] ]
+ bounds: [ [ 13.088345, 52.3382448 ], [ 13.7611609, 52.6755087 ] ],
+ outline: expect.any(Function)
},
// Named by the leading part of its label, Nominatim having named it nothing itself, and
- // framed by nothing, its extent being unreadable.
- { id: "4", label: "Paris, France", name: "Paris", lat: 48.8566, lng: 2.3522, bounds: undefined }
+ // framed by nothing: its extent is unreadable, and a node has no boundary to fetch.
+ {
+ id: "4", label: "Paris, France", name: "Paris", lat: 48.8566, lng: 2.3522,
+ bounds: undefined, outline: undefined
+ }
]);
});
@@ -96,6 +102,31 @@ describe("Nominatim geocoding", () => {
await refused;
});
+ it("fetches the boundary of a place on its own, simplified, only when it is asked for", async () => {
+ const fetchMock = respondWith([ place() ]);
+ const [ berlin ] = await search("berlin");
+ expect(fetchMock).toHaveBeenCalledOnce();
+
+ const boundary: GeoJSON.Geometry = { type: "MultiPolygon", coordinates: [] };
+ respondWith([ { geojson: boundary } ]);
+ const outlineFetch = berlin.outline?.();
+ await vi.runAllTimersAsync();
+
+ expect(await outlineFetch).toEqual(boundary);
+ });
+
+ it("draws no boundary for a shape that is not one", async () => {
+ respondWith([ place() ]);
+ const [ berlin ] = await search("berlin");
+
+ // A point is what the pin already says; there is nothing to ring.
+ respondWith([ { geojson: { type: "Point", coordinates: [ 13.4, 52.5 ] } } ]);
+ const outlineFetch = berlin.outline?.();
+ await vi.runAllTimersAsync();
+
+ expect(await outlineFetch).toBeNull();
+ });
+
it("holds searches to the one request a second the usage policy allows", async () => {
const requestedAt: number[] = [];
vi.stubGlobal("fetch", vi.fn(async () => {
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.ts
index bcc44b1e03..58ea3481c0 100644
--- a/apps/client/src/widgets/collections/geomap/nominatim.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts
@@ -2,6 +2,19 @@ import { getCurrentLanguage } from "../../../services/i18n";
import type { GeocodingProvider, GeoSearchResult } from "./geocoding";
const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";
+const NOMINATIM_LOOKUP_URL = "https://nominatim.openstreetmap.org/lookup";
+
+/**
+ * How coarsely a boundary is simplified, in degrees — roughly 100 m. At full detail a country runs to
+ * megabytes, and a border drawn over a map is not read to the metre.
+ */
+const POLYGON_THRESHOLD = 0.001;
+
+/**
+ * How a lookup names an OSM object, from how a search result names one. Nodes are left out: a place
+ * that is a single point has no boundary, and its pin already says where it is.
+ */
+const OSM_TYPE_PREFIX: Record<string, string> = { relation: "R", way: "W" };
/** Caps how many results one search returns. */
const MAX_RESULTS = 8;
@@ -58,6 +71,8 @@ async function searchNominatim(query: string): Promise<GeoSearchResult[]> {
/** One entry of a Nominatim `jsonv2` response, narrowed to the fields a result is built from. */
interface NominatimPlace {
place_id?: number;
+ osm_type?: string;
+ osm_id?: number;
display_name?: string;
name?: string;
lat?: string;
@@ -74,6 +89,9 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {
return null;
}
+ const prefix = OSM_TYPE_PREFIX[place.osm_type ?? ""];
+ const osmId = prefix && place.osm_id ? `${prefix}${place.osm_id}` : null;
+
return {
id: String(place.place_id ?? `${lat},${lng}`),
label: place.display_name,
@@ -82,7 +100,8 @@ function toSearchResult(place: NominatimPlace): GeoSearchResult | null {
name: place.name || place.display_name.split(",")[0].trim(),
lat,
lng,
- bounds: toBounds(place.boundingbox)
+ bounds: toBounds(place.boundingbox),
+ outline: osmId ? () => fetchOutline(osmId) : undefined
};
}
@@ -106,6 +125,32 @@ function toBounds(boundingbox: string[] | undefined): GeoSearchResult["bounds"]
return [ [ west, south ], [ east, north ] ];
}
+/**
+ * The boundary of one OSM object, simplified, or `null` where it has none to draw.
+ *
+ * A lookup of its own rather than `polygon_geojson` on the search: a search answers with eight places
+ * and the boundaries of the seven that go unlooked-at are the bulk of what would be carried.
+ */
+async function fetchOutline(osmId: string): Promise<GeoJSON.Geometry | null> {
+ const params = new URLSearchParams({
+ osm_ids: osmId,
+ format: "jsonv2",
+ polygon_geojson: "1",
+ polygon_threshold: String(POLYGON_THRESHOLD)
+ });
+
+ await waitForRequestSlot();
+ const response = await fetch(`${NOMINATIM_LOOKUP_URL}?${params}`);
+ if (!response.ok) {
+ throw new Error(`Nominatim answered ${response.status} ${response.statusText}`);
+ }
+
+ const [ place ]: { geojson?: GeoJSON.Geometry }[] = await response.json();
+ const geometry = place?.geojson;
+ // A shape that is a point or a line is what the pin already says, drawn again.
+ return geometry?.type === "Polygon" || geometry?.type === "MultiPolygon" ? geometry : null;
+}
+
/**
* Holds a request back until the interval the policy asks for has passed since the last one.
*