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
feat(geomap): go to a point named in the search bar
Elian Doranb95cfe4cf498
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 7d09ef476d..1bab308dca 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2966,7 +2966,8 @@"previous-result": "Previous result","next-result": "Next result","result-position": "Result {{index}} of {{total}}, click to return to it",- "results-on-map": "On this map"+ "results-on-map": "On this map",+ "go-to-coordinates": "Go to {{- coordinates}}"},"embedded_note": {"open-note": "Open note",diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsxindex f416b44717..0dbed7fec8 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx@@ -247,6 +247,24 @@ describe("geo map SearchBox", () => {expect(map.fitBounds).not.toHaveBeenCalled();});+ it("offers a point named outright, above whatever was searched for", async () => {+ mockGeocoder([]);+ const map = fakeMap();+ const container = renderSearchBox(map, mapNotes());++ await type(container, "45.9432, 24.9668");++ // Above the rest: the reader named where they were going rather than looked for it.+ expect(labels()[0]).toBe("geo-map.go-to-coordinates(45.9432, 24.9668)");++ await pick(0);++ // Pinned and offered for keeping as a searched place is, and shown as closely as it was+ // meant rather than at the level a place of unsaid extent gets.+ expect(pickedPlace()).toMatchObject({ name: "45.9432, 24.9668", lat: 45.9432, lng: 24.9668 });+ expect(map.flyTo).toHaveBeenCalledWith({ center: [ 24.9668, 45.9432 ], zoom: 16 });+ });+it("offers nothing for a query below the minimum length", async () => {const container = renderSearchBox(fakeMap(), mapNotes());diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsxindex b197ae9649..4927f972e8 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx@@ -14,6 +14,7 @@ import { filterTokens, matchesFilter } from "../../react/filter";import FormAutocomplete from "../../react/FormAutocomplete";import Icon from "../../react/Icon";import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";+import { formatCoordinates, parseCoordinates } from "./coordinates";import { DEFAULT_GEOCODING_PROVIDER_NAME, DEFAULT_PLACE_ICON, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";import { GPX_MIME } from "./GpxTrack";import { ParentMap } from "./map";@@ -48,6 +49,12 @@ const EARTH_RADIUS_M = 6_371_008.8;*/const RESULT_LIST_WIDTH = 500;+/**+ * How close a point named by its coordinates is shown. Nearer than the level a place of unsaid+ * extent is given: coordinates are typed to reach one spot rather than the town around it.+ */+const POINT_ZOOM = 16;+/** Caps how many of the map's own notes the list offers. */const MAX_MARKER_RESULTS = 8;@@ -84,6 +91,12 @@ type SearchEntry = {| { kind: "marker"; center?: [number, number]; noteId: string }/** A place from the geocoder, carried whole for whoever the pick is reported to. */| { kind: "place"; center: [number, number]; result: GeoSearchResult }+ /**+ * A point the query names outright. Carried as a place, which is what it is taken as, but a row+ * of its own: what it says is what taking it does, the coordinates being what the reader just+ * typed rather than something found for them.+ */+ | { kind: "point"; center: [number, number]; result: GeoSearchResult }/** Names the run of rows below it; not a choice (see `isHeading` on FormAutocomplete). */| { kind: "heading" }/** Runs the geocoder for `query`. */@@ -146,7 +159,14 @@ export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {const { places, notice } = geocodeEntries(geocodeRun, trimmed, provider.name);const found = [ ...matchMarkers(notes, trimmed), ...places ].map((entry) => withDistance(entry, origin));- const entries = [ ...grouped(found), ...(notice ? [ notice ] : []) ];+ // Above the groups rather than sorted into them: a reader who typed a point named where+ // they were going, and what a search turned up answers a different question.+ const point = pointEntry(trimmed);+ const entries = [+ ...(point ? [ withDistance(point, origin) ] : []),+ ...grouped(found),+ ...(notice ? [ notice ] : [])+ ];entriesByKey.current = new Map(entries.map((entry) => [ entry.key, entry ]));return entries.map((entry) => entry.key);}, [ notes, geocodeRun, dismissed, map, provider ]);@@ -209,7 +229,7 @@ export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {if (entry.kind === "geocode") {runGeocoder(entry.query);- } else if (entry.kind === "marker" || entry.kind === "place") {+ } else if (entry.kind === "marker" || entry.kind === "place" || entry.kind === "point") {setDismissed(true);// The whole of what was offered, so the map can step through the rest of it once the@@ -301,7 +321,7 @@ function walkableResults(entries: Map<string, SearchEntry>): SearchResult[] {for (const entry of entries.values()) {if (entry.kind === "marker") {results.push({ kind: "note", noteId: entry.noteId, center: entry.center });- } else if (entry.kind === "place") {+ } else if (entry.kind === "place" || entry.kind === "point") {results.push({ kind: "place", place: entry.result });}}@@ -456,6 +476,39 @@ function headingEntry(key: string, label: string): SearchEntry {return { kind: "heading", key: `heading:${key}`, label };}+/**+ * The row for a point the query names outright, or `null` where it names none.+ *+ * A place like any the geocoder answers with, so that taking it pins it, offers it for keeping and+ * steps among the rest exactly as a searched place does — one without a name, which is why it is+ * named by its own coordinates.+ */+function pointEntry(query: string): SearchEntry | null {+ const center = parseCoordinates(query);+ if (!center) {+ return null;+ }++ const [ lng, lat ] = center;+ const coordinates = formatCoordinates(center);++ return {+ kind: "point",+ key: `place:point:${lng},${lat}`,+ label: t("geo-map.go-to-coordinates", { coordinates }),+ icon: "bx bx-crosshair",+ center,+ result: {+ id: `point:${lng},${lat}`,+ name: coordinates,+ label: coordinates,+ lat,+ lng,+ zoom: POINT_ZOOM+ }+ };+}+function placeEntry(result: GeoSearchResult): SearchEntry {return {kind: "place",diff --git a/apps/client/src/widgets/collections/geomap/coordinates.spec.ts b/apps/client/src/widgets/collections/geomap/coordinates.spec.tsnew file mode 100644index 0000000000..d28d2dacb3--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/coordinates.spec.ts@@ -0,0 +1,73 @@+/**+ * Reading a point out of the search bar: which of the forms a reader arrives with name one, and+ * what does not name one at all.+ */+import { describe, expect, it } from "vitest";++import { formatCoordinates, parseCoordinates } from "./coordinates";++/** Sibiu, as each form writes it. Held as `[lng, lat]`, which is how the map holds a point. */+const SIBIU: [number, number] = [ 24.9668, 45.9432 ];++describe("reading a point out of the search bar", () => {+ it("reads a bare pair, however it is separated", () => {+ // What both Google Maps and OpenStreetMap hand over when asked for a place's coordinates,+ // and what `#geolocation` holds.+ expect(parseCoordinates("45.9432, 24.9668")).toEqual(SIBIU);+ expect(parseCoordinates("45.9432,24.9668")).toEqual(SIBIU);+ expect(parseCoordinates("45.9432 24.9668")).toEqual(SIBIU);+ expect(parseCoordinates(" 45.9432 , 24.9668 ")).toEqual(SIBIU);+ });++ it("reads a point south and west of nowhere", () => {+ expect(parseCoordinates("-33.8688, -151.2093")).toEqual([ -151.2093, -33.8688 ]);+ expect(parseCoordinates("+45.9432, +24.9668")).toEqual(SIBIU);+ // A whole number of degrees is still a point.+ expect(parseCoordinates("45, 24")).toEqual([ 24, 45 ]);+ expect(parseCoordinates("0, 0")).toEqual([ 0, 0 ]);+ });++ it("reads the URI the map offers a place under", () => {+ expect(parseCoordinates("geo:45.9432,24.9668")).toEqual(SIBIU);+ // The zoom and uncertainty a `geo:` URI can carry are somebody else's business.+ expect(parseCoordinates("geo:45.9432,24.9668?z=15")).toEqual(SIBIU);+ expect(parseCoordinates("geo:45.9432,24.9668;u=35")).toEqual(SIBIU);+ });++ it("reads the URL of the two sites the guide sends a reader to", () => {+ expect(parseCoordinates("https://www.openstreetmap.org/#map=15/45.9432/24.9668"))+ .toEqual(SIBIU);+ expect(parseCoordinates("https://www.openstreetmap.org/?mlat=45.9432&mlon=24.9668"))+ .toEqual(SIBIU);+ expect(parseCoordinates("https://www.google.com/maps/@45.9432,24.9668,15z")).toEqual(SIBIU);+ expect(parseCoordinates("https://maps.google.com/?q=45.9432,24.9668")).toEqual(SIBIU);+ // A place named in the URL as well as placed in it is still gone to by where it stands.+ expect(parseCoordinates("https://www.google.com/maps/place/Sibiu/@45.9432,24.9668,15z"))+ .toEqual(SIBIU);+ });++ it("passes over what does not name a point", () => {+ expect(parseCoordinates("")).toBeNull();+ expect(parseCoordinates("London")).toBeNull();+ // One number is half a point, and a house number is none of one.+ expect(parseCoordinates("45.9432")).toBeNull();+ expect(parseCoordinates("45 Main Street")).toBeNull();+ expect(parseCoordinates("Cafe 45, 24")).toBeNull();+ });++ it("passes over a pair that stands off the Earth", () => {+ // A pair of numbers a reader is looking for rather than somewhere to be flown to.+ expect(parseCoordinates("1234, 5678")).toBeNull();+ expect(parseCoordinates("91, 24")).toBeNull();+ expect(parseCoordinates("45, 181")).toBeNull();+ // The edges themselves are still on it.+ expect(parseCoordinates("90, 180")).toEqual([ 180, 90 ]);+ expect(parseCoordinates("-90, -180")).toEqual([ -180, -90 ]);+ });++ it("names a point by the coordinates as they were typed", () => {+ // Rather than padded out to a fixed precision: four decimals were meant as four.+ expect(formatCoordinates(SIBIU)).toBe("45.9432, 24.9668");+ expect(formatCoordinates([ 0, 0 ])).toBe("0, 0");+ });+});diff --git a/apps/client/src/widgets/collections/geomap/coordinates.ts b/apps/client/src/widgets/collections/geomap/coordinates.tsnew file mode 100644index 0000000000..c220c5e288--- /dev/null+++ b/apps/client/src/widgets/collections/geomap/coordinates.ts@@ -0,0 +1,71 @@+/**+ * Reading a point out of what was typed into the search bar, so a pair of coordinates can be gone+ * to as directly as a place can be searched for.+ *+ * The forms understood are the ones a reader arrives with: a bare pair, as both Google Maps and+ * OpenStreetMap hand over when asked for a place's coordinates and as `#geolocation` holds them;+ * the `geo:` URI the map itself offers a place under (see the location actions in DetailPane and+ * ContextMenus); and the URLs of those two sites, which are what a reader copies when they have+ * not gone looking for the coordinates at all.+ */++/** How far north or south a point can stand, and how far east or west. */+const MAX_LATITUDE = 90;+const MAX_LONGITUDE = 180;++/** A decimal number, signed or not, as every form below spells one. */+const NUMBER = String.raw`[+-]?\d+(?:\.\d+)?`;++/**+ * The forms a point is written in, each holding the latitude first and the longitude second.+ *+ * Ordered from the most exact to the loosest: a bare pair is the whole of what was typed, while the+ * URL forms are looked for within it, and `@lat,lng` would otherwise be read out of a Google Maps+ * URL that also carries the place it stands for.+ */+const FORMS = [+ /** A bare pair, separated by a comma or by spaces: `45.9432, 24.9668`. */+ new RegExp(String.raw`^(${NUMBER})\s*(?:,\s*|\s+)(${NUMBER})$`),+ /** The `geo:` URI, whose zoom and uncertainty parameters are left to whoever wants them. */+ new RegExp(String.raw`^geo:(${NUMBER}),(${NUMBER})`, "i"),+ /** OpenStreetMap's marker link: `?mlat=45.9432&mlon=24.9668`. */+ new RegExp(String.raw`[?&]mlat=(${NUMBER})&mlon=(${NUMBER})`, "i"),+ /** OpenStreetMap's view, which its address bar carries: `#map=15/45.9432/24.9668`. */+ new RegExp(String.raw`#map=${NUMBER}/(${NUMBER})/(${NUMBER})`, "i"),+ /** What Google Maps puts a query under: `?q=45.9432,24.9668`. */+ new RegExp(String.raw`[?&](?:q|query|ll)=(${NUMBER}),(${NUMBER})`, "i"),+ /** Where Google Maps says the view stands: `/@45.9432,24.9668,15z`. */+ new RegExp(String.raw`@(${NUMBER}),(${NUMBER})`)+];++/**+ * The point `query` names, as `[lng, lat]` — the order the map holds a position in (see+ * `parseLocation` in Markers) — or `null` for anything that does not name one.+ *+ * A pair that stands off the Earth is not a point: `1234, 5678` is a pair of numbers a reader is+ * looking for rather than somewhere to be flown to.+ */+export function parseCoordinates(query: string): [number, number] | null {+ const trimmed = query.trim();++ for (const form of FORMS) {+ const match = form.exec(trimmed);+ if (!match) continue;++ const lat = Number(match[1]);+ const lng = Number(match[2]);+ if (Math.abs(lat) > MAX_LATITUDE || Math.abs(lng) > MAX_LONGITUDE) continue;++ return [ lng, lat ];+ }++ return null;+}++/**+ * A point as it is named on the map and in the list: the coordinates as they were typed rather than+ * padded out to a fixed precision, a reader who typed four decimals having meant four.+ */+export function formatCoordinates([ lng, lat ]: [number, number]) {+ return `${lat}, ${lng}`;+}diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.tsindex 7930f83e3d..6a8fbcee6a 100644--- a/apps/client/src/widgets/collections/geomap/geocoding.ts+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts@@ -53,6 +53,11 @@ export interface GeoSearchResult {* by their extent rather than by one zoom level guessed for both.*/bounds?: GeoBounds;+ /**+ * How close the place asks to be shown, for one that knows better than the guess made for+ * a place of unsaid extent: a point named by its coordinates is meant exactly.+ */+ zoom?: 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.diff --git a/apps/client/src/widgets/collections/geomap/results.ts b/apps/client/src/widgets/collections/geomap/results.tsindex 9c5579b95e..aaf3f9ca15 100644--- a/apps/client/src/widgets/collections/geomap/results.ts+++ b/apps/client/src/widgets/collections/geomap/results.ts@@ -32,6 +32,9 @@ const PLACE_PADDING = 60;** A GPX track is left to the pane, which fits its whole route once the line is on the map (see* DetailPane) — a route is a shape, and there is no one point to fly to.+ *+ * A place asking for a zoom of its own is shown at it, which is how a point named by its+ * coordinates is shown as closely as it was meant rather than at the level a town is.*/export function frameResult(map: MapLibreGLMap, result: SearchResult) {if (result.kind === "place" && result.place.bounds) {@@ -46,5 +49,8 @@ export function frameResult(map: MapLibreGLMap, result: SearchResult) {return;}- map.flyTo({ center: [ result.place.lng, result.place.lat ], zoom: PLACE_ZOOM });+ map.flyTo({+ center: [ result.place.lng, result.place.lat ],+ zoom: result.place.zoom ?? PLACE_ZOOM+ });}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.htmlindex add3dfb7a5..3064549929 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map.html@@ -83,6 +83,22 @@of the same name on another continent. The view is treated as at least 25 kmacross, so searching while zoomed into a single street still covers the townaround it.</p>+<h3>Going to a point</h3>+<p>Coordinates typed or pasted into the search bar are offered as a <em>Go to</em> row+ above everything else, and taking it flies the map to that exact spot and+ marks it, so it can be kept as a marker in the same way a searched place+ can.</p>+<p>The forms understood are:</p>+<ul>+ <li>A plain pair, <code spellcheck="false">45.9432, 24.9668</code> — what both Google Maps and+ OpenStreetMap give when asked for a place's coordinates, and what the+ <code spellcheck="false">#geolocation</code> attribute holds.</li>+ <li>The <code spellcheck="false">geo:</code> link the map itself offers a place under, from the+ <em>Open location</em> action.</li>+ <li>The address of a place on Google Maps or OpenStreetMap, pasted whole.</li>+</ul>+<p>A pair that is not a place on Earth, such as <code spellcheck="false">1234, 5678</code>, is not+ offered.</p><h3>Reading the results</h3><p>Results are gathered under headings, and each group is ordered by distancefrom the middle of the map:</p>diff --git a/docs/User Guide/User Guide/Collections/Geo Map.md b/docs/User Guide/User Guide/Collections/Geo Map.mdindex 3bd258db13..4f63fad069 100644--- a/docs/User Guide/User Guide/Collections/Geo Map.md+++ b/docs/User Guide/User Guide/Collections/Geo Map.md@@ -58,6 +58,18 @@ Trilium uses Nominatim, the place search run by the OpenStreetMap Foundation. ItThe search prefers what the map is showing. Places inside the current view are looked for first and listed above the rest, so searching for a shop while looking at your own town finds the branch in that town rather than one of the same name on another continent. The view is treated as at least 25 km across, so searching while zoomed into a single street still covers the town around it.+### Going to a point++Coordinates typed or pasted into the search bar are offered as a _Go to_ row above everything else, and taking it flies the map to that exact spot and marks it, so it can be kept as a marker in the same way a searched place can.++The forms understood are:++* A plain pair, `45.9432, 24.9668` — what both Google Maps and OpenStreetMap give when asked for a place's coordinates, and what the `#geolocation` attribute holds.+* The `geo:` link the map itself offers a place under, from the _Open location_ action.+* The address of a place on Google Maps or OpenStreetMap, pasted whole.++A pair that is not a place on Earth, such as `1234, 5678`, is not offered.+### Reading the resultsResults are gathered under headings, and each group is ordered by distance from the middle of the map: