Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): coordinate rulers along an image map's edges

Elian Doranea33da6b44eb
diff --git a/apps/client/src/widgets/collections/geomap/ImageRulers.spec.ts b/apps/client/src/widgets/collections/geomap/ImageRulers.spec.ts
new file mode 100644
index 0000000000..6a0f59cc2d
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ImageRulers.spec.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from "vitest";
+
+import { axisTicks, niceStep, rulerFeatures } from "./ImageRulers";
+import { imageSpace, parseImageExtent } from "./space";
+
+describe("niceStep", () => {
+ it("rounds up to 1, 2 or 5 times a power of ten", () => {
+ expect(niceStep(0.7)).toBe(1);
+ expect(niceStep(1)).toBe(1);
+ expect(niceStep(1.3)).toBe(2);
+ expect(niceStep(3)).toBe(5);
+ expect(niceStep(7)).toBe(10);
+ expect(niceStep(130)).toBe(200);
+ expect(niceStep(0.03)).toBeCloseTo(0.05, 12);
+ });
+});
+
+describe("axisTicks", () => {
+ it("spaces round values at least 90 screen pixels apart, edges included", () => {
+ // 1000 units over 1000 image pixels, drawn one to one: 90 units → a step of 100.
+ expect(axisTicks(0, 1000, 1000, 1).map(({ value }) => value)).toEqual([ 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 ]);
+ // Zoomed in four times: 22.5 units → 50.
+ const zoomed = axisTicks(0, 1000, 1000, 4).map(({ value }) => value);
+ expect(zoomed.slice(0, 3)).toEqual([ 0, 50, 100 ]);
+ expect(zoomed).toHaveLength(21);
+ });
+
+ it("works either way round, across zero, and labels without stray digits or a minus zero", () => {
+ const ticks = axisTicks(512, -512, 1024, 1);
+ expect(ticks.map(({ value }) => value)).toEqual([ -500, -400, -300, -200, -100, 0, 100, 200, 300, 400, 500 ]);
+ expect(ticks.find(({ value }) => value === 0)?.text).toBe("0");
+
+ // 0.09 units → a step of 0.1, which floating point would otherwise print as 0.30000000000000004.
+ const fine = axisTicks(0, 1, 1000, 1);
+ expect(fine.map(({ text }) => text)).toEqual([ "0", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1" ]);
+ });
+});
+
+describe("rulerFeatures", () => {
+ it("draws a grid line, two ticks and a label per value, and the image's outline", () => {
+ const space = imageSpace({ width: 1000, height: 500 }, parseImageExtent("-2000,1000 2000,-1000"));
+ const { features } = rulerFeatures(space, 1);
+ const byKind = (kind: string) => features.filter((feature) => feature.properties?.kind === kind);
+
+ // A step of 500 both ways: 9 values across, 5 down.
+ const labels = byKind("label");
+ expect(labels.map((feature) => feature.properties?.label)).toEqual([
+ "-2000", "-1500", "-1000", "-500", "0", "500", "1000", "1500", "2000",
+ "-1000", "-500", "0", "500", "1000"
+ ]);
+ expect(byKind("grid")).toHaveLength(14);
+ expect(byKind("tick")).toHaveLength(14 * 2 + 1);
+
+ // y grows upwards: the label for 1000 stands beside the top edge, -1000 beside the bottom.
+ const yLabel = (text: string) => {
+ const feature = labels.find((candidate) => candidate.properties?.anchor === "right" && candidate.properties?.label === text);
+ if (feature?.geometry.type !== "Point") throw new Error(`no label ${text}`);
+ return feature.geometry.coordinates;
+ };
+ expect(yLabel("1000")[1]).toBeCloseTo(space.pixelToLngLat([ 0, 0 ])[1], 9);
+ expect(yLabel("-1000")[1]).toBeCloseTo(space.pixelToLngLat([ 0, 500 ])[1], 9);
+ });
+});
diff --git a/apps/client/src/widgets/collections/geomap/ImageRulers.tsx b/apps/client/src/widgets/collections/geomap/ImageRulers.tsx
new file mode 100644
index 0000000000..76e9e4c785
--- /dev/null
+++ b/apps/client/src/widgets/collections/geomap/ImageRulers.tsx
@@ -0,0 +1,227 @@
+import type { GeoJSONSource, Map as MapLibreGLMap } from "maplibre-gl";
+import { useContext, useEffect } from "preact/hooks";
+
+import { CLUSTER_LAYER } from "./clusters";
+import { MapStyleLoaded, ParentMap } from "./map";
+import { MARKER_LAYER, SELECTION_LAYER } from "./Markers";
+import type { ImageSpace } from "./space";
+
+const RULER_SOURCE = "image-rulers";
+const GRID_LAYER = "image-rulers-grid";
+const TICK_LAYER = "image-rulers-ticks";
+const LABEL_LAYER = "image-rulers-labels";
+
+/** The screen distance labels are spaced at, at least: the step is the next round number past it. */
+const LABEL_SPACING_PX = 90;
+/** How far a tick reaches out from the image's edge, in screen pixels. */
+const TICK_LENGTH_PX = 6;
+/** The gap between a tick's end and its label, in screen pixels. */
+const LABEL_GAP_PX = 3;
+
+/**
+ * Coordinate rulers along an image map's edges, in the map's own coordinates (see
+ * `#map:imageBounds`): a tick and a label at every round value on the top and left edges, bare ticks
+ * on the bottom and right ones, and faint grid lines across the image.
+ *
+ * Drawn by MapLibre as one GeoJSON source, so the rulers move with the image. The step and the
+ * ticks' length depend on the zoom, so the data is rebuilt as the map zooms.
+ */
+export default function ImageRulers({ space, isDarkTheme }: { space: ImageSpace; isDarkTheme: boolean }) {
+ const map = useContext(ParentMap);
+ const styleLoaded = useContext(MapStyleLoaded);
+
+ useEffect(() => {
+ if (!map || !styleLoaded) return;
+
+ const colors = rulerColors(map.getContainer(), isDarkTheme);
+ const build = () => rulerFeatures(space, screenScale(map, space));
+
+ function add() {
+ if (!map) return;
+ try {
+ if (!map.getSource(RULER_SOURCE)) {
+ map.addSource(RULER_SOURCE, { type: "geojson", data: build() });
+ }
+
+ // Under the markers, which are added either before or after these.
+ const beforeId = [ CLUSTER_LAYER, SELECTION_LAYER, MARKER_LAYER ].find((id) => map.getLayer(id));
+ if (!map.getLayer(GRID_LAYER)) {
+ map.addLayer({
+ id: GRID_LAYER,
+ type: "line",
+ source: RULER_SOURCE,
+ filter: [ "==", [ "get", "kind" ], "grid" ],
+ paint: { "line-color": colors.grid, "line-width": 1 }
+ }, beforeId);
+ }
+ if (!map.getLayer(TICK_LAYER)) {
+ map.addLayer({
+ id: TICK_LAYER,
+ type: "line",
+ source: RULER_SOURCE,
+ filter: [ "==", [ "get", "kind" ], "tick" ],
+ paint: { "line-color": colors.text, "line-width": 1 }
+ }, beforeId);
+ }
+ if (!map.getLayer(LABEL_LAYER)) {
+ map.addLayer({
+ id: LABEL_LAYER,
+ type: "symbol",
+ source: RULER_SOURCE,
+ filter: [ "==", [ "get", "kind" ], "label" ],
+ layout: {
+ "text-field": [ "get", "label" ],
+ "text-font": [ "Open Sans Regular" ],
+ "text-size": 11,
+ "text-anchor": [ "get", "anchor" ],
+ // Spaced by the step already, and never to be dropped for a marker's title.
+ "text-allow-overlap": true,
+ "text-ignore-placement": true
+ },
+ paint: {
+ "text-color": colors.text,
+ "text-halo-color": colors.halo,
+ "text-halo-width": 1
+ }
+ }, beforeId);
+ }
+ } catch (e) {
+ console.warn("Geo map: could not draw the rulers —", e);
+ }
+ }
+
+ // One rebuild per frame, however many zoom events arrive in it.
+ let frame = 0;
+ function update() {
+ cancelAnimationFrame(frame);
+ frame = requestAnimationFrame(() => map?.getSource<GeoJSONSource>(RULER_SOURCE)?.setData(build()));
+ }
+
+ add();
+ map.on("style.load", add);
+ map.on("zoom", update);
+
+ return () => {
+ cancelAnimationFrame(frame);
+ map.off("style.load", add);
+ map.off("zoom", update);
+ try {
+ for (const layer of [ LABEL_LAYER, TICK_LAYER, GRID_LAYER ]) {
+ if (map.getLayer(layer)) {
+ map.removeLayer(layer);
+ }
+ }
+ if (map.getSource(RULER_SOURCE)) {
+ map.removeSource(RULER_SOURCE);
+ }
+ } catch {
+ // The map may already have been removed.
+ }
+ };
+ }, [ map, styleLoaded, space, isDarkTheme ]);
+
+ return null;
+}
+
+/**
+ * The rulers as GeoJSON: grid lines across the image, ticks out from its edges and a label past
+ * every tick on the top and left edges.
+ *
+ * Built in the image's pixels, measured from its top-left corner, and converted to `[lng, lat]`
+ * last, so flipped axes and axes of different scales need no special handling.
+ *
+ * @param screenPerImagePixel how many screen pixels one pixel of the image takes at the current zoom.
+ */
+export function rulerFeatures(space: ImageSpace, screenPerImagePixel: number): GeoJSON.FeatureCollection {
+ const { size: { width, height }, extent: { topLeft: [ left, top ], bottomRight: [ right, bottom ] } } = space;
+ const tick = TICK_LENGTH_PX / screenPerImagePixel;
+ const labelAt = (TICK_LENGTH_PX + LABEL_GAP_PX) / screenPerImagePixel;
+ const features: GeoJSON.Feature[] = [];
+
+ const line = (kind: "grid" | "tick", from: [number, number], to: [number, number]) => features.push({
+ type: "Feature",
+ properties: { kind },
+ geometry: { type: "LineString", coordinates: [ space.pixelToLngLat(from), space.pixelToLngLat(to) ] }
+ });
+ const label = (text: string, anchor: "bottom" | "right", at: [number, number]) => features.push({
+ type: "Feature",
+ properties: { kind: "label", label: text, anchor },
+ geometry: { type: "Point", coordinates: space.pixelToLngLat(at) }
+ });
+
+ for (const { value, text } of axisTicks(left, right, width, screenPerImagePixel)) {
+ const x = ((value - left) / (right - left)) * width;
+ line("grid", [ x, 0 ], [ x, height ]);
+ line("tick", [ x, 0 ], [ x, -tick ]);
+ line("tick", [ x, height ], [ x, height + tick ]);
+ label(text, "bottom", [ x, -labelAt ]);
+ }
+
+ for (const { value, text } of axisTicks(top, bottom, height, screenPerImagePixel)) {
+ const y = ((value - top) / (bottom - top)) * height;
+ line("grid", [ 0, y ], [ width, y ]);
+ line("tick", [ 0, y ], [ -tick, y ]);
+ line("tick", [ width, y ], [ width + tick, y ]);
+ label(text, "right", [ -labelAt, y ]);
+ }
+
+ // The image's outline, which the ticks stand on.
+ const corners: [number, number][] = [ [ 0, 0 ], [ width, 0 ], [ width, height ], [ 0, height ], [ 0, 0 ] ];
+ features.push({
+ type: "Feature",
+ properties: { kind: "tick" },
+ geometry: { type: "LineString", coordinates: corners.map(space.pixelToLngLat) }
+ });
+
+ return { type: "FeatureCollection", features };
+}
+
+/**
+ * The round values along one axis that get a tick, from the edge at `from` to the one at `to` (either
+ * way round), with the text each is labeled with.
+ */
+export function axisTicks(from: number, to: number, pixels: number, screenPerImagePixel: number) {
+ const unitsPerScreenPixel = Math.abs(to - from) / pixels / screenPerImagePixel;
+ const step = niceStep(unitsPerScreenPixel * LABEL_SPACING_PX);
+ const decimals = Math.max(0, Math.ceil(-Math.log10(step)));
+ const low = Math.min(from, to);
+ const high = Math.max(from, to);
+
+ const ticks: { value: number; text: string }[] = [];
+ // A hair of slack, so an edge that falls on a round value keeps its tick despite rounding.
+ const slack = step * 1e-9;
+ for (let i = Math.ceil((low - slack) / step); i * step <= high + slack; i++) {
+ const value = Number((i * step).toFixed(decimals));
+ // `+ 0` turns a negative zero into a plain one, which would otherwise print as "-0".
+ ticks.push({ value, text: String(value + 0) });
+ }
+ return ticks;
+}
+
+/** The smallest of 1, 2 and 5 times a power of ten that is at least `raw`. */
+export function niceStep(raw: number) {
+ const power = 10 ** Math.floor(Math.log10(raw));
+ const fraction = raw / power;
+ const nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10;
+ return nice * power;
+}
+
+/** How many screen pixels a pixel of the image takes at the map's current zoom. */
+function screenScale(map: MapLibreGLMap, space: ImageSpace) {
+ const start = map.project(space.pixelToLngLat([ 0, 0 ]));
+ const end = map.project(space.pixelToLngLat([ space.size.width, 0 ]));
+ return Math.hypot(end.x - start.x, end.y - start.y) / space.size.width;
+}
+
+/**
+ * The ticks and labels stand mostly outside the image, over the page around it, so they take the
+ * app's own text colors. The grid lines lie over the image, so they follow `#map:darkStyle`.
+ */
+function rulerColors(container: HTMLElement, isDarkTheme: boolean) {
+ const style = getComputedStyle(container);
+ return {
+ text: style.getPropertyValue("--main-text-color").trim() || "#333",
+ halo: style.getPropertyValue("--main-background-color").trim() || "#fff",
+ grid: isDarkTheme ? "rgba(255, 255, 255, 0.2)" : "rgba(0, 0, 0, 0.15)"
+ };
+}
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index be5d585ea7..0e35615a17 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -24,6 +24,7 @@ import DrawShape, { DrawTool } from "./DrawShape";
import DrawToolbar from "./DrawToolbar";
import EditToolbar from "./EditToolbar";
import GhostPin from "./GhostPin";
+import ImageRulers from "./ImageRulers";
import { GPX_MIME, GpxTrack } from "./GpxTrack";
import type { GeoSearchResult } from "./geocoding";
import Map, { type CameraLimits, DEFAULT_ZOOM, GeoMouseEvent } from "./map";
@@ -493,6 +494,8 @@ export default function GeoView({ note, noteIds, viewConfig, saveConfig }: ViewM
{/* Stood up only while the view is leaned over, so the 3D button changes the map
and not merely the angle it is seen from. */}
{isGeo && <Buildings isDarkTheme={layerData.isDarkTheme ?? false} />}
+ {/* The scale an image map has instead of a distance in meters. */}
+ {image && hasScale && <ImageRulers space={image.space} isDarkTheme={layerData.isDarkTheme ?? false} />}
{/* The places the base map itself draws answer a click, which is a marker named and
placed without typing either (see Pois). */}
{isGeo && <Pois placing={!!placement} onPick={pickPlace} />}
diff --git a/apps/client/src/widgets/collections/geomap/space.ts b/apps/client/src/widgets/collections/geomap/space.ts
index 9c89718ef7..eee911a330 100644
--- a/apps/client/src/widgets/collections/geomap/space.ts
+++ b/apps/client/src/widgets/collections/geomap/space.ts
@@ -154,6 +154,14 @@ export interface ImageSpace extends MapSpace {
maxBounds: Bounds;
/** The deepest zoom worth having: a few levels past the one that draws a pixel per pixel. */
maxZoom: number;
+ /** The image's natural size. */
+ size: ImageSize;
+ /** The coordinates of the image's corners, the image's own pixels where the map names none. */
+ extent: ImageExtent;
+ /** A position in the map's coordinates as `[lng, lat]`, unrounded. */
+ toLngLat(point: [number, number]): [number, number];
+ /** A position in the image's pixels, from its top-left corner, as `[lng, lat]`. */
+ pixelToLngLat(pixel: [number, number]): [number, number];
}
/**
@@ -224,6 +232,10 @@ export function imageSpace({ width, height }: ImageSize, extent?: ImageExtent |
maxBounds: [ [ west, south ], [ east, north ] ],
// MapLibre's world is 512 pixels across at zoom 0, and doubles with each level.
maxZoom: Math.log2(longerSide / (IMAGE_EXTENT * 512)) + IMAGE_OVERZOOM,
+ size: { width, height },
+ extent: { topLeft: [ left, top ], bottomRight: [ right, bottom ] },
+ toLngLat,
+ pixelToLngLat,
parseLocation(value) {
const point = parsePair(value);
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
index eab240cdc7..fdbc9b2b00 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Collections/Geo Map/Image maps.html
@@ -33,7 +33,7 @@ class="admonition note">
<li>Going to your location.</li>
<li>Adding GPS tracks.</li>
<li>Clicking the places the base map shows.</li>
- <li>The 3D buildings and the scale.</li>
+ <li>The 3D buildings.</li>
<li>Opening a location in an external map application.</li>
</ul>
<p>The look of the marker titles follows the image: if the image is dark,
@@ -63,6 +63,16 @@ class="admonition note">
stretched differently along the two axes.</p>
<p>A value that cannot be read, or whose corners share an <code>x</code> or
a <code>y</code>, is ignored and the pixels of the image are used instead.</p>
+<h2>Coordinate rulers</h2>
+<p>Enabling <em>Show scale</em> in the collection properties draws rulers along
+ the edges of the image instead of a distance scale. Round values of the
+ map's coordinates are marked with ticks along all four edges, labeled along
+ the top and left ones, with faint grid lines across the image. The spacing
+ follows the zoom level, and the values follow <code>#map:imageBounds</code> when
+ it is set.</p>
+<p>The rulers are drawn on the image itself, so they move out of view along
+ with its edges when zooming in. The grid lines remain visible across the
+ image.</p>
<h2>How the positions are stored</h2>
<p>Because positions are stored in different labels from the ones of a geo
map, the same note can be placed both on a geo map and on an image map.</p>
diff --git a/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md b/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
index 898ddbddf8..5bdbce447c 100644
--- a/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
+++ b/docs/User Guide/User Guide/Collections/Geo Map/Image maps.md
@@ -22,7 +22,7 @@ The features that only make sense on a real map are not available on an image ma
* Going to your location.
* Adding GPS tracks.
* Clicking the places the base map shows.
-* The 3D buildings and the scale.
+* The 3D buildings.
* Opening a location in an external map application.
The look of the marker titles follows the image: if the image is dark, add the `#map:darkStyle` label to the geo map so that the titles are drawn in a light color.
@@ -41,6 +41,12 @@ The two axes don't have to use the same scale. A circle is always measured in th
A value that cannot be read, or whose corners share an `x` or a `y`, is ignored and the pixels of the image are used instead.
+## Coordinate rulers
+
+Enabling _Show scale_ in the collection properties draws rulers along the edges of the image instead of a distance scale. Round values of the map's coordinates are marked with ticks along all four edges, labeled along the top and left ones, with faint grid lines across the image. The spacing follows the zoom level, and the values follow `#map:imageBounds` when it is set.
+
+The rulers are drawn on the image itself, so they move out of view along with its edges when zooming in. The grid lines remain visible across the image.
+
## How the positions are stored
Because positions are stored in different labels from the ones of a geo map, the same note can be placed both on a geo map and on an image map.