Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): frame a map around its markers where no view has been saved

Elian Doranbb406ed858e0
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
index 97f3d3a4e6..afa771cd29 100644
--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx
+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx
@@ -18,6 +18,7 @@ import { useLegacyComponentElement, useNoteColorClass, useNoteLabel, useStaticTo
import Modal from "../../react/Modal";
import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";
import { removeFromMap } from "./api";
+import { type Bounds, boundsOf } from "./coordinates";
import { GPX_MIME, trackHitLayers, trackSourceId } from "./GpxTrack";
import { ParentMap } from "./map";
import { formatLocation, LOCATION_ATTRIBUTE, MARKER_LAYER, parseLocation } from "./Markers";
@@ -350,54 +351,29 @@ function featureFocus(feature: MapGeoJSONFeature): PaneFocus | undefined {
* its flags stand on its line, and another journey's ground — or a waypoint hung off in a third
* place — is exactly what focusing one track is meant to leave out of frame.
*
- * Longitude is read in two frames at once, because it is a circle wearing a seam: a track across
- * the antimeridian holds points either side of ±180° that are a stroll apart on the ground, and
- * their raw minimum and maximum span nearly the whole world. The same longitudes are therefore
- * also read with the seam moved to 0° — each western value pushed a turn east — and the shifted
- * frame answers where it draws the narrower box.
- *
- * Only a box wider than half the world is reconsidered, that being the width a crossing of the seam
- * produces. Anything narrower is already whole, and the two widths are then equal to within what
- * floating point does to them, which is enough to send a track in Florida round the far side of the
- * world. The shifted answer may name longitudes past 180°, which `fitBounds` takes in stride.
+ * The seam at ±180° is {@link boundsOf}'s to deal with, which the points are yielded to as they are
+ * read: a long ride holds thousands of them.
*/
-async function trackBounds(map: MapLibreGLMap, noteId: string, track?: number): Promise<[[number, number], [number, number]] | null> {
+async function trackBounds(map: MapLibreGLMap, noteId: string, track?: number): Promise<Bounds | null> {
const data = await map.getSource<GeoJSONSource>(trackSourceId(noteId))?.getData();
if (!data || data.type !== "FeatureCollection") return null;
+ const { features } = data;
+
+ function* points() {
+ for (const { geometry, properties } of features) {
+ if (track !== undefined && properties?.track !== track) continue;
- let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;
- let westShifted = Infinity, eastShifted = -Infinity;
- const extend = ([ lng, lat ]: number[]) => {
- west = Math.min(west, lng);
- south = Math.min(south, lat);
- east = Math.max(east, lng);
- north = Math.max(north, lat);
-
- const shifted = lng < 0 ? lng + 360 : lng;
- westShifted = Math.min(westShifted, shifted);
- eastShifted = Math.max(eastShifted, shifted);
- };
-
- for (const { geometry, properties } of data.features) {
- if (track !== undefined && properties?.track !== track) continue;
-
- if (geometry.type === "Point") {
- extend(geometry.coordinates);
- } else if (geometry.type === "MultiLineString") {
- for (const line of geometry.coordinates) {
- for (const point of line) {
- extend(point);
+ if (geometry.type === "Point") {
+ yield geometry.coordinates;
+ } else if (geometry.type === "MultiLineString") {
+ for (const line of geometry.coordinates) {
+ yield* line;
}
}
}
}
- if (!Number.isFinite(west)) return null;
-
- const spansHalfTheWorld = east - west > 180;
- return spansHalfTheWorld && eastShifted - westShifted < east - west
- ? [ [ westShifted, south ], [ eastShifted, north ] ]
- : [ [ west, south ], [ east, north ] ];
+ return boundsOf(points());
}
/**
diff --git a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
index d959f45c28..5e45a67e85 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.spec.tsx
@@ -23,7 +23,7 @@ import { buildNote } from "../../../test/easy-froca";
import { ParentComponent } from "../../react/react_utils";
import { CLUSTER_COUNT_LAYER, CLUSTER_LAYER } from "./clusters";
import { MapStyleLoaded, ParentMap } from "./map";
-import Markers, { formatLocation, MARKER_LAYER, MARKER_SOURCE, parseLocation, SELECTION_LAYER } from "./Markers";
+import Markers, { FitToNotes, formatLocation, MARKER_LAYER, MARKER_SOURCE, parseLocation, SELECTION_LAYER } from "./Markers";
vi.mock("../../../services/icon_glyphs", () => ({
renderIconImage: vi.fn(async () => "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=")
@@ -52,6 +52,7 @@ function fakeMap() {
const listeners = new Map<string, Set<Listener>>();
const calls = { addLayer: 0, removeLayer: 0, addSource: 0, removeSource: 0, setData: 0 };
const properties = new Map<string, unknown>();
+ const fits: { bounds: unknown, options: unknown }[] = [];
const canvas = { style: {} as Record<string, string> };
let lastFeatures: unknown[] = [];
let removed = false;
@@ -145,7 +146,10 @@ function fakeMap() {
setPaintProperty(id: string, name: string, value: unknown) { properties.set(`${id}/${name}`, value); },
// Filed with the properties: what a layer's filter has been repointed to is read the same
// way as what it has been repainted with.
- setFilter(id: string, filter: unknown) { properties.set(`${id}/filter`, filter); }
+ setFilter(id: string, filter: unknown) { properties.set(`${id}/filter`, filter); },
+ /** Every framing the map has been asked for, in the order it was asked. */
+ get fits() { return fits; },
+ fitBounds(bounds: unknown, options: unknown) { fits.push({ bounds, options }); }
};
}
@@ -699,3 +703,84 @@ describe("reading and writing a place", () => {
expect(coordinates && formatLocation(coordinates, 15)).toBe("48.855653506551015, 2.365492536863660");
});
});
+
+describe("framing a map around its notes", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ function mountFit(notes: FNote[], map: ReturnType<typeof fakeMap>, enabled = true) {
+ return act(async () => {
+ render(
+ <ParentMap.Provider value={map as never}>
+ <FitToNotes notes={notes} enabled={enabled} />
+ </ParentMap.Provider>,
+ container
+ );
+ });
+ }
+
+ const PARIS = buildNote({ title: "Paris", "#geolocation": "48.8566,2.3522" });
+ const BERLIN = buildNote({ title: "Berlin", "#geolocation": "52.52,13.405" });
+ const UNPLACED = buildNote({ title: "Somewhere in particular" });
+
+ it("frames the notes that have a place, and leaves out the ones that have none", async () => {
+ const map = fakeMap();
+
+ await mountFit([ PARIS, UNPLACED, BERLIN ], map);
+
+ expect(map.fits).toHaveLength(1);
+ expect(map.fits[0].bounds).toEqual([ [ 2.3522, 48.8566 ], [ 13.405, 52.52 ] ]);
+ // A single note would otherwise fit at whatever zoom solves a box with no width, and a map
+ // that flew to its own notes would show the stock view first.
+ expect(map.fits[0].options).toMatchObject({ maxZoom: expect.any(Number), animate: false });
+ });
+
+ it("leaves a map that has a saved view exactly where the reader put it", async () => {
+ const map = fakeMap();
+
+ await mountFit([ PARIS, BERLIN ], map, false);
+
+ expect(map.fits).toHaveLength(0);
+ });
+
+ it("does not move a map that holds nothing with a place", async () => {
+ const map = fakeMap();
+
+ await mountFit([ UNPLACED ], map);
+ await mountFit([], map);
+
+ expect(map.fits).toHaveLength(0);
+ });
+
+ it("frames once, so a note arriving later cannot pull the camera back", async () => {
+ const map = fakeMap();
+
+ await mountFit([ PARIS ], map);
+ expect(map.fits).toHaveLength(1);
+
+ // The reader has since moved the map; a note gaining a place must not undo that.
+ await mountFit([ PARIS, BERLIN ], map);
+ expect(map.fits).toHaveLength(1);
+ });
+
+ it("waits for the notes rather than framing an empty map and giving up", async () => {
+ const map = fakeMap();
+
+ // The collection has not loaded yet, which is what every map looks like on its first render.
+ await mountFit([], map);
+ expect(map.fits).toHaveLength(0);
+
+ await mountFit([ PARIS, BERLIN ], map);
+ expect(map.fits).toHaveLength(1);
+ expect(map.fits[0].bounds).toEqual([ [ 2.3522, 48.8566 ], [ 13.405, 52.52 ] ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/Markers.tsx b/apps/client/src/widgets/collections/geomap/Markers.tsx
index 2ed67b2688..6fac1fd32a 100644
--- a/apps/client/src/widgets/collections/geomap/Markers.tsx
+++ b/apps/client/src/widgets/collections/geomap/Markers.tsx
@@ -8,7 +8,9 @@ import { getReadableTextColor } from "../../../services/css_class_manager";
import { renderIconImage } from "../../../services/icon_glyphs";
import { useTriliumEvent } from "../../react/hooks";
import { CLUSTER_LAYERS, CLUSTER_SOURCE_OPTIONS, installClusterLayers, UNCLUSTERED_ONLY, useClusterExpansion } from "./clusters";
+import { boundsOf } from "./coordinates";
import { MapStyleLoaded, ParentMap } from "./map";
+import { NOTE_ZOOM } from "./results";
export { GEO_LOCATION_ATTRIBUTE as LOCATION_ATTRIBUTE } from "@triliumnext/commons";
export const MARKER_LAYER = "points-layer";
@@ -107,6 +109,9 @@ const SELECTION_GLOW_PAINT = {
/** The glow's reach in screen pixels, a little wider than the grown pin standing over it. */
const SELECTION_GLOW_RADIUS = 18;
+/** Air left around the notes a map is framed around, so no pin sits on the viewport's edge. */
+const FIT_PADDING = 48;
+
/**
* Every note that carries a location, drawn as one symbol layer.
*
@@ -454,6 +459,57 @@ function useMarkerOpening(map: MapLibreGLMap | null, enabled: boolean) {
}, [ map, enabled ]);
}
+/**
+ * Points the camera at the notes a map holds, on a map that has never been positioned.
+ *
+ * A map opened at the stock view stands over an ocean, and its notes are found by panning until
+ * they turn up — which is what a map filled in by a script asks of every reader who opens it.
+ * Framing them is what the reader would do by hand, done once and saved as any other view is.
+ *
+ * Only where `enabled`, which the view above passes as "no view has been saved": where one has, it
+ * is where the reader put the map and is never overruled. Only once per map besides, so a note
+ * gaining a place while the map is open cannot pull the camera off wherever the reader has since
+ * moved it.
+ *
+ * The framing is a camera move like any other, so the `moveend` behind it saves the view — the next
+ * open reads it back rather than working it out again.
+ *
+ * A component rather than an effect in the view above, so the map is read from the context every
+ * other layer reads it from. Nothing is drawn.
+ */
+export function FitToNotes({ notes, enabled }: { notes: FNote[], enabled: boolean }) {
+ const map = useContext(ParentMap);
+ const framed = useRef(false);
+
+ useEffect(() => {
+ if (!map || !enabled || framed.current) return;
+
+ const bounds = boundsOf(locationsOf(notes));
+ if (!bounds) return;
+
+ framed.current = true;
+ // One note draws a box with no width, which fits at whatever zoom the camera can be solved
+ // for — the whole world, in practice. `maxZoom` stands it on its street instead, at the
+ // level the detail pane goes to a marker at.
+ //
+ // Not animated: this is where the map opens, not somewhere it is taken. Flying would show
+ // the stock view first and swoop off it every time a map is opened for the first time.
+ map.fitBounds(bounds, { padding: FIT_PADDING, maxZoom: NOTE_ZOOM, animate: false });
+ }, [ map, notes, enabled ]);
+
+ return null;
+}
+
+/** Every place a map's notes stand, in the `[lng, lat]` a box is drawn from. */
+function* locationsOf(notes: FNote[]) {
+ for (const note of notes) {
+ const location = parseLocation(note.getLabelValue(GEO_LOCATION_ATTRIBUTE));
+ if (location) {
+ yield location;
+ }
+ }
+}
+
/**
* A GeoJSON feature per located note, and the pin image each of them asks for.
*
diff --git a/apps/client/src/widgets/collections/geomap/coordinates.spec.ts b/apps/client/src/widgets/collections/geomap/coordinates.spec.ts
index d28d2dacb3..21659d3d5d 100644
--- a/apps/client/src/widgets/collections/geomap/coordinates.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/coordinates.spec.ts
@@ -4,7 +4,7 @@
*/
import { describe, expect, it } from "vitest";
-import { formatCoordinates, parseCoordinates } from "./coordinates";
+import { boundsOf, 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 ];
@@ -71,3 +71,33 @@ describe("reading a point out of the search bar", () => {
expect(formatCoordinates([ 0, 0 ])).toBe("0, 0");
});
});
+
+describe("boxing a set of points", () => {
+ it("draws the box the points fit into, and nothing for no points at all", () => {
+ expect(boundsOf([ [ 10, 40 ], [ 20, 50 ], [ 15, 30 ] ])).toEqual([ [ 10, 30 ], [ 20, 50 ] ]);
+ // One point is a box with no width, which is what the caller's maxZoom is for.
+ expect(boundsOf([ SIBIU ])).toEqual([ SIBIU, SIBIU ]);
+ expect(boundsOf([])).toBeNull();
+ });
+
+ it("takes the short way round the seam rather than the long way round the world", () => {
+ // Either side of the antimeridian, a stroll apart on the ground. Read raw they span nearly
+ // the whole world; the western one is pushed a turn east so the box stays narrow.
+ expect(boundsOf([ [ 179, -17 ], [ -179, -18 ] ])).toEqual([ [ 179, -18 ], [ 181, -17 ] ]);
+ });
+
+ it("leaves a box narrower than half the world in the frame it was read in", () => {
+ // Florida, west of the meridian and nowhere near the seam. Shifting it would send it round
+ // the far side of the world, so a narrow box is never reconsidered.
+ expect(boundsOf([ [ -81, 25 ], [ -80, 26 ] ])).toEqual([ [ -81, 25 ], [ -80, 26 ] ]);
+ // Europe, which straddles the meridian and so holds longitudes of both signs.
+ expect(boundsOf([ [ -9, 38 ], [ 24, 60 ] ])).toEqual([ [ -9, 38 ], [ 24, 60 ] ]);
+ // Exactly half the world is still whole.
+ expect(boundsOf([ [ -90, 0 ], [ 90, 10 ] ])).toEqual([ [ -90, 0 ], [ 90, 10 ] ]);
+ });
+
+ it("frames three points across the seam by the ground between them", () => {
+ // The seam is a circle's, not a pair's: the far side is the long way round for all of them.
+ expect(boundsOf([ [ 170, 0 ], [ -170, 5 ], [ 178, 2 ] ])).toEqual([ [ 170, 0 ], [ 190, 5 ] ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/coordinates.ts b/apps/client/src/widgets/collections/geomap/coordinates.ts
index c220c5e288..aee79a24d6 100644
--- a/apps/client/src/widgets/collections/geomap/coordinates.ts
+++ b/apps/client/src/widgets/collections/geomap/coordinates.ts
@@ -1,6 +1,6 @@
/**
- * 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.
+ * Points on the map: reading one out of what a reader typed, writing one back, and boxing a set of
+ * them so the camera can be pointed at all of them at once.
*
* 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;
@@ -69,3 +69,46 @@ export function parseCoordinates(query: string): [number, number] | null {
export function formatCoordinates([ lng, lat ]: [number, number]) {
return `${lat}, ${lng}`;
}
+
+/** The corners of a box, as `fitBounds` wants them: south-west first, north-east second. */
+export type Bounds = [[number, number], [number, number]];
+
+/**
+ * The box a set of `[lng, lat]` points fits into, or `null` where there are no points.
+ *
+ * Longitude is read in two frames at once, because it is a circle wearing a seam: points either
+ * side of ±180° are a stroll apart on the ground, and their raw minimum and maximum span nearly the
+ * whole world. The same longitudes are therefore also read with the seam moved to 0° — each western
+ * value pushed a turn east — and the shifted frame answers where it draws the narrower box.
+ *
+ * Only a box wider than half the world is reconsidered, that being the width a crossing of the seam
+ * produces. Anything narrower is already whole, and the two widths are then equal to within what
+ * floating point does to them, which is enough to send a set of points in Florida round the far
+ * side of the world. The shifted answer may name longitudes past 180°, which `fitBounds` takes in
+ * stride.
+ *
+ * Takes an iterable so a caller with many points — a GPX track holds thousands — can yield them as
+ * they are read rather than gather them into an array first.
+ */
+export function boundsOf(points: Iterable<number[]>): Bounds | null {
+ let west = Infinity, south = Infinity, east = -Infinity, north = -Infinity;
+ let westShifted = Infinity, eastShifted = -Infinity;
+
+ for (const [ lng, lat ] of points) {
+ west = Math.min(west, lng);
+ south = Math.min(south, lat);
+ east = Math.max(east, lng);
+ north = Math.max(north, lat);
+
+ const shifted = lng < 0 ? lng + 360 : lng;
+ westShifted = Math.min(westShifted, shifted);
+ eastShifted = Math.max(eastShifted, shifted);
+ }
+
+ if (!Number.isFinite(west)) return null;
+
+ const spansHalfTheWorld = east - west > 180;
+ return spansHalfTheWorld && eastShifted - westShifted < east - west
+ ? [ [ westShifted, south ], [ eastShifted, north ] ]
+ : [ [ west, south ], [ east, north ] ];
+}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index d630ed99b1..c242601c16 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -24,7 +24,7 @@ import Map, { DEFAULT_ZOOM, GeoMouseEvent } from "./map";
import { DEFAULT_MAP_LAYER_NAME, MAP_LAYERS, MapLayer } from "./map_layer";
import MapToolbar from "./MapToolbar";
import type { GeoSearchResult } from "./geocoding";
-import Markers, { DEFAULT_MARKER_COLOR, LOCATION_ATTRIBUTE } from "./Markers";
+import Markers, { DEFAULT_MARKER_COLOR, FitToNotes, LOCATION_ATTRIBUTE } from "./Markers";
import PlaceMarker from "./PlaceMarker";
import PlacePanel from "./PlacePanel";
import Pois from "./Pois";
@@ -33,7 +33,15 @@ import { NOTE_ZOOM, type SearchResult } from "./results";
import SearchBox from "./SearchBox";
import Tooltips from "./Tooltips";
-const DEFAULT_COORDINATES: [number, number] = [3.878638227135724, 446.6630455551659];
+/**
+ * Where a map stands when there is nothing to stand it on: no view has been saved and no note it
+ * holds has a place. Latitude first, as {@link MapData} holds a centre.
+ *
+ * A little north of the equator on the prime meridian, which at {@link DEFAULT_ZOOM} is most of the
+ * inhabited world. A map that holds located notes never opens here — it frames them instead (see
+ * {@link FitToNotes}).
+ */
+const DEFAULT_COORDINATES: [number, number] = [20, 0];
/**
* The instruction toast that says what the map is waiting for. One id for both kinds of placement:
@@ -420,6 +428,7 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
raising the quick editor over the pane that had just opened behind it. */}
<Markers notes={notes} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} clustered={clustered} placing={!!placement} opensNotes={false} selectedNoteId={selection?.noteId ?? null} />
{notes.map(note => <NoteGpxTrackWrapper note={note} hideLabels={hideLabels} isDarkTheme={layerData.isDarkTheme ?? false} />)}
+ <FitToNotes notes={notes} enabled={!viewConfig?.view} />
</Map>}
</div>
);
diff --git a/docs/User Guide/User Guide/Collections/Geo Map.md b/docs/User Guide/User Guide/Collections/Geo Map.md
index 0b54a779e8..58bed0d817 100644
--- a/docs/User Guide/User Guide/Collections/Geo Map.md
+++ b/docs/User Guide/User Guide/Collections/Geo Map.md
@@ -40,6 +40,10 @@ By default the map will be empty and will show the entire world.
The position on the map and the zoom are saved inside the map note and restored when visiting again the note.
+A map that has no position saved yet is framed around the markers it contains when you open it, so they are all in view without having to go looking for them. A map that contains no markers shows the whole world instead.
+
+In practice this applies to maps whose markers were added externally, by a script or through <a class="reference-link" href="../Advanced%20Usage/ETAPI%20(REST%20API).md">ETAPI (REST API)</a>. When you add markers yourself you have already moved the map to reach the place you are marking, and that movement saves a position.
+
## Searching the map
The search bar at the top-left of the map searches in two places. It always searches the notes that are already on the map. It can also search for places online, but only when you ask it to.