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): name an image map's coordinate system with #map:imageBounds
Elian Doran83ff3804247c
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsxindex 76db089183..056eac8393 100644--- a/apps/client/src/widgets/collections/geomap/index.tsx+++ b/apps/client/src/widgets/collections/geomap/index.tsx@@ -38,7 +38,7 @@ import { NOTE_ZOOM, type SearchResult } from "./results";import SearchBox from "./SearchBox";import { ShapeLayer, ShapeNames } from "./ShapeLayer";import type { GeoShape } from "./shapes";-import { geoSpace, type ImageSize, imageSpace, type ImageSpace, MapSpaceContext } from "./space";+import { geoSpace, type ImageSize, imageSpace, type ImageSpace, MapSpaceContext, parseImageExtent } from "./space";import Tooltips from "./Tooltips";/**@@ -544,16 +544,17 @@ type ImageMapState =function useImageMap(note: FNote): ImageMapState {const [ imageNoteId ] = useNoteRelation(note, "map:image");- const [ state, setState ] = useState<ImageMapState>(imageNoteId ? { status: "loading" } : { status: "geo" });+ const [ boundsValue ] = useNoteLabel(note, "map:imageBounds");+ const [ image, setImage ] = useState<LoadedImage>(imageNoteId ? { status: "loading" } : { status: "geo" });useEffect(() => {if (!imageNoteId) {- setState({ status: "geo" });+ setImage({ status: "geo" });return;}let cancelled = false;- setState({ status: "loading" });+ setImage({ status: "loading" });(async () => {const imageNote = await froca.getNote(imageNoteId, true);@@ -565,18 +566,27 @@ function useImageMap(note: FNote): ImageMapState {if (!url || !size) {logError(`The image ${imageNoteId} of map ${note.noteId} could not be loaded.`);- setState({ status: "error" });+ setImage({ status: "error" });return;}- setState({ status: "image", url, space: imageSpace(size) });+ setImage({ status: "image", url, size });})();return () => { cancelled = true; };}, [ note.noteId, imageNoteId ]);- return state;+ // Built apart from the loading, so naming the corners anew does not fetch the image again.+ // A value that names no corners is read as none, which leaves the image's own pixels.+ return useMemo(() => image.status === "image"+ ? { status: "image", url: image.url, space: imageSpace(image.size, parseImageExtent(boundsValue)) }+ : image, [ image, boundsValue ]);}+/** {@link ImageMapState} before the coordinate system is laid over the measured image. */+type LoadedImage =+ | Exclude<ImageMapState, { status: "image" }>+ | { status: "image"; url: string; size: ImageSize };+/** The natural size of the image at `url`, or `null` where it does not load as one. */function measureImage(url: string): Promise<ImageSize | null> {return new Promise((resolve) => {diff --git a/apps/client/src/widgets/collections/geomap/space.spec.ts b/apps/client/src/widgets/collections/geomap/space.spec.tsindex 657fb44f0c..b9dba8f76b 100644--- a/apps/client/src/widgets/collections/geomap/space.spec.ts+++ b/apps/client/src/widgets/collections/geomap/space.spec.ts@@ -2,7 +2,7 @@ import { MercatorCoordinate } from "maplibre-gl";import { describe, expect, it } from "vitest";import { buildNote } from "../../../test/easy-froca";-import { geoSpace, imageSpace, isShapeNote, locationOf, shapeOf } from "./space";+import { geoSpace, imageSpace, isShapeNote, locationOf, parseImageExtent, shapeOf } from "./space";describe("geoSpace", () => {it("stores latitude first and hands MapLibre longitude first", () => {@@ -83,6 +83,73 @@ describe("imageSpace", () => {});});+describe("imageSpace with named corners", () => {+ const size = { width: 1000, height: 500 };+ // A y-up world whose origin is the middle of the image, as a game map often is.+ const extent = parseImageExtent("-2000,1000 2000,-1000");+ const space = imageSpace(size, extent);+ const pixels = imageSpace(size);++ it("puts the corners and the origin where the map names them", () => {+ expect(space.parseLocation("-2000,1000")).toEqual(pixels.parseLocation("0,0"));+ expect(space.parseLocation("2000,-1000")).toEqual(pixels.parseLocation("1000,500"));+ expect(space.parseLocation("0,0")).toEqual(pixels.parseLocation("500,250"));+ // Up is up: a larger y stands higher on the image.+ const higher = space.parseLocation("0,500");+ const origin = space.parseLocation("0,0");+ expect(higher && origin && higher[1] > origin[1]).toBe(true);+ });++ it("stores what it reads, rounded to a hundredth of a pixel and shown to a whole one", () => {+ const point = space.parseLocation("123.456,-78.9");+ if (!point) throw new Error("unreadable");+ // 4 units a pixel: a hundredth of a pixel is 0.04, which takes two decimals.+ expect(space.serializeLocation(point)).toBe("123.46,-78.9");+ expect(space.formatLocation(point)).toBe("123, -79");+ expect(space.formatLocation(point, true)).toBe("123.46, -78.9");++ const fine = imageSpace(size, parseImageExtent("0,0 1,0.5"));+ const finePoint = fine.parseLocation("0.123456,0.25");+ if (!finePoint) throw new Error("unreadable");+ expect(fine.serializeLocation(finePoint)).toBe("0.12346,0.25");+ });++ it("keeps a marker on the same ground when the image is replaced by a larger one", () => {+ const larger = imageSpace({ width: 4000, height: 2000 }, extent);+ const pixelsOfLarger = imageSpace({ width: 4000, height: 2000 });++ expect(larger.parseLocation("1000,500")).toEqual(space.parseLocation("1000,500"));+ expect(pixelsOfLarger.formatLocation(larger.parseLocation("1000,500") ?? [ 0, 0 ])).toBe("3000, 500");+ });++ it("measures circles in the map's units, as an ellipse where the axes differ", () => {+ // 1 unit a pixel across, 4 units a pixel down.+ const stretched = imageSpace(size, parseImageExtent("0,0 1000,2000"));+ const shape = shapeOrThrow(stretched.parseShape("circle:500,1000 200"));+ if (shape.type !== "circle" || !shape.ring) throw new Error("expected a circle with a ring");++ const ringPixels = shape.ring.map((point) => pixels.serializeLocation(point).split(",").map(Number));+ const width = Math.max(...ringPixels.map(([ x ]) => x)) - Math.min(...ringPixels.map(([ x ]) => x));+ const height = Math.max(...ringPixels.map(([ , y ]) => y)) - Math.min(...ringPixels.map(([ , y ]) => y));+ expect(width).toBeCloseTo(400, 0);+ expect(height).toBeCloseTo(100, 0);++ expect(stretched.serializeShape(shape)).toBe("circle:500,1000 200");+ for (const value of [ "line:-2000,1000 0,0", "polygon:0,0 100,0 100,-50" ]) {+ expect(space.serializeShape(shapeOrThrow(space.parseShape(value)))).toBe(value);+ }+ });++ it("reads corners only where both are pairs spanning something", () => {+ expect(parseImageExtent("-2000,1000 2000,-1000")).toEqual({ topLeft: [ -2000, 1000 ], bottomRight: [ 2000, -1000 ] });+ expect(parseImageExtent(" 0,0 10,5 ")).toEqual({ topLeft: [ 0, 0 ], bottomRight: [ 10, 5 ] });+ // Four numbers in a row are not two corners.+ for (const value of [ "", "0,0", "0,0 10", "0,0 0,5", "0,0 10,0", "a,b c,d", "0,0 1,1 2,2", "-100,-100,1200,512", null, undefined ]) {+ expect(parseImageExtent(value)).toBeNull();+ }+ });+});+function shapeOrThrow<T>(shape: T | null): T {if (!shape) throw new Error("unreadable shape");return shape;diff --git a/apps/client/src/widgets/collections/geomap/space.ts b/apps/client/src/widgets/collections/geomap/space.tsindex 959ed068da..7656092532 100644--- a/apps/client/src/widgets/collections/geomap/space.ts+++ b/apps/client/src/widgets/collections/geomap/space.ts@@ -1,10 +1,11 @@/**- * What a map's coordinates are: places on the Earth, or pixels on an image.+ * What a map's coordinates are: places on the Earth, or positions on an image.** MapLibre knows only longitude and latitude, so everything on the map is held in `[lng, lat]`* whichever it is. A {@link MapSpace} converts at the edge, where a position is read off a note's* label or written back onto one: a geo map stores `#geolocation` and `#geoShape` in degrees, an- * image map `#imagePosition` and `#imageShape` in the image's own pixels (see {@link imageSpace}).+ * image map `#imagePosition` and `#imageShape` in a coordinate system the map names for its image+ * (see {@link imageSpace}).*/import { GEO_LOCATION_ATTRIBUTE, GEO_SHAPE_ATTRIBUTE, IMAGE_POSITION_ATTRIBUTE, IMAGE_SHAPE_ATTRIBUTE } from "@triliumnext/commons";@@ -101,6 +102,16 @@ export interface ImageSize {height: number;}+/**+ * The coordinates an image map's own system gives the image's top-left and bottom-right corners,+ * as `#map:imageBounds` names them. Either axis can run either way: a top-left `y` larger than the+ * bottom-right one is a world whose `y` grows upwards.+ */+export interface ImageExtent {+ topLeft: [number, number];+ bottomRight: [number, number];+}+/*** Where the image stands in MapLibre's world: its top-left corner, and how much of the world its* longer side spans, both in Mercator units (the world being 0–1 each way).@@ -118,8 +129,9 @@ const IMAGE_MARGIN = 0.25;/** How many zoom levels past the image's own resolution the camera can go. */const IMAGE_OVERZOOM = 2;-/** The decimals a pixel coordinate keeps: a hundredth of a pixel is finer than any click lands. */-const PIXEL_DECIMALS = 2;+/** How finely a stored coordinate resolves the image, in parts of a pixel: a hundredth of a pixel+ * is finer than any click lands. */+const STORED_PARTS_OF_PIXEL = 100;export interface ImageSpace extends MapSpace {kind: "image";@@ -135,57 +147,83 @@ export interface ImageSpace extends MapSpace {}/**- * The space of a map drawn over an image of the given size, which stores pixels measured from the- * image's top-left corner, `x` to the right and `y` downwards.+ * The space of a map drawn over an image of the given size, which stores positions in a coordinate+ * system of the map's own choosing: `extent` names the coordinates of the image's corners, and every+ * position is stored in those, so coordinates taken from a game or a survey are used unchanged.+ * Without an extent the corners are `0,0` and the image's size, which stores pixels measured from+ * the top-left corner, `x` to the right and `y` downwards.+ *+ * Positions belong to the coordinate system rather than to the image, so a replacement image keeps+ * every marker in place once its corners are named for the ground it covers.** The image is laid onto MapLibre's world in Mercator units rather than degrees. Mercator units are* what MapLibre draws in, so a pixel maps to them linearly and the image is drawn without the* stretching that latitude would put on it. MapTiler's image viewer places its images the same way.*/-export function imageSpace({ width, height }: ImageSize): ImageSpace {+export function imageSpace({ width, height }: ImageSize, extent?: ImageExtent | null): ImageSpace {+ const { topLeft: [ left, top ], bottomRight: [ right, bottom ] } = extent ?? {+ topLeft: [ 0, 0 ],+ bottomRight: [ width, height ]+ };const longerSide = Math.max(width, height);- const unitsPerPixel = IMAGE_EXTENT / longerSide;-- function toLngLat([ x, y ]: [number, number]): [number, number] {+ const mercatorPerPixel = IMAGE_EXTENT / longerSide;+ // Signed: a negative step is an axis running the other way from the image's pixels.+ const unitsPerPixelX = (right - left) / width;+ const unitsPerPixelY = (bottom - top) / height;+ // Stored to a hundredth of a pixel on the finer axis, shown to a whole one.+ const finestUnit = Math.min(Math.abs(unitsPerPixelX), Math.abs(unitsPerPixelY));+ const storedDecimals = decimalsFor(finestUnit / STORED_PARTS_OF_PIXEL);+ const shownDecimals = decimalsFor(finestUnit);++ function pixelToLngLat([ px, py ]: [number, number]): [number, number] {const { lng, lat } = new MercatorCoordinate(- IMAGE_ORIGIN + x * unitsPerPixel,- IMAGE_ORIGIN + y * unitsPerPixel+ IMAGE_ORIGIN + px * mercatorPerPixel,+ IMAGE_ORIGIN + py * mercatorPerPixel).toLngLat();return [ lng, lat ];}- function toPixel([ lng, lat ]: [number, number]): [number, number] {+ function toLngLat([ x, y ]: [number, number]): [number, number] {+ return pixelToLngLat([ (x - left) / unitsPerPixelX, (y - top) / unitsPerPixelY ]);+ }++ /** A `[lng, lat]` position in the map's coordinates, unrounded. */+ function toWorld([ lng, lat ]: [number, number]): [number, number] {const { x, y } = MercatorCoordinate.fromLngLat({ lng, lat });return [- roundPixel((x - IMAGE_ORIGIN) / unitsPerPixel),- roundPixel((y - IMAGE_ORIGIN) / unitsPerPixel)+ left + ((x - IMAGE_ORIGIN) / mercatorPerPixel) * unitsPerPixelX,+ top + ((y - IMAGE_ORIGIN) / mercatorPerPixel) * unitsPerPixelY];}+ const round = (value: number) => roundTo(value, storedDecimals);+ const toStored = (point: [number, number]) => toWorld(point).map(round) as [number, number];+const margin = longerSide * IMAGE_MARGIN;- const [ west, north ] = toLngLat([ -margin, -margin ]);- const [ east, south ] = toLngLat([ width + margin, height + margin ]);- const topLeft = toLngLat([ 0, 0 ]);- const bottomRight = toLngLat([ width, height ]);+ const [ west, north ] = pixelToLngLat([ -margin, -margin ]);+ const [ east, south ] = pixelToLngLat([ width + margin, height + margin ]);+ const topLeftLngLat = pixelToLngLat([ 0, 0 ]);+ const bottomRightLngLat = pixelToLngLat([ width, height ]);return {kind: "image",locationAttribute: IMAGE_POSITION_ATTRIBUTE,shapeAttribute: IMAGE_SHAPE_ATTRIBUTE,- corners: [ topLeft, toLngLat([ width, 0 ]), bottomRight, toLngLat([ 0, height ]) ],- bounds: [ [ topLeft[0], bottomRight[1] ], [ bottomRight[0], topLeft[1] ] ],+ corners: [ topLeftLngLat, pixelToLngLat([ width, 0 ]), bottomRightLngLat, pixelToLngLat([ 0, height ]) ],+ bounds: [ [ topLeftLngLat[0], bottomRightLngLat[1] ], [ bottomRightLngLat[0], topLeftLngLat[1] ] ],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,parseLocation(value) {- const point = parsePixel(value);+ const point = parsePair(value);return point && toLngLat(point);},- serializeLocation: (point) => toPixel(point).join(","),+ serializeLocation: (point) => toStored(point).join(","),formatLocation(point, full) {- const [ x, y ] = toPixel(point);- return full ? `${x}, ${y}` : `${Math.round(x)}, ${Math.round(y)}`;+ const [ x, y ] = toWorld(point);+ const decimals = full ? storedDecimals : shownDecimals;+ return `${roundTo(x, decimals)}, ${roundTo(y, decimals)}`;},parseShape(value) {@@ -193,15 +231,18 @@ export function imageSpace({ width, height }: ImageSize): ImageSpace {if (!written) return null;if (written.type === "circle") {- const [ centerPixel ] = written.points;- const center = toLngLat(centerPixel);+ const [ centerWorld ] = written.points;+ const center = toLngLat(centerWorld);+ const ring = worldCircle(centerWorld, written.radius).map(toLngLat);+ const centerMercator = MercatorCoordinate.fromLngLat({ lng: center[0], lat: center[1] });return {type: "circle",center,- // Exact at the centre, which is all a radius in meters can be on a flat image.- radiusMeters: written.radius * unitsPerPixel- / MercatorCoordinate.fromLngLat({ lng: center[0], lat: center[1] }).meterInMercatorCoordinateUnits(),- ring: pixelCircle(centerPixel, written.radius).map(toLngLat)+ // The ring's mean reach, in meters at the centre. The ring is an ellipse on+ // the image where the two axes' units differ.+ radiusMeters: meanDistance(ring.map(toMercator), [ centerMercator.x, centerMercator.y ])+ / centerMercator.meterInMercatorCoordinateUnits(),+ ring};}@@ -211,20 +252,40 @@ export function imageSpace({ width, height }: ImageSize): ImageSpace {serializeShape(shape) {if (shape.type === "circle") {// Read back off the ring rather than the radius in meters, so a circle keeps the- // size it was drawn at wherever on the image it stands.- const ring = shapeRing(shape).map(toPixel);+ // size it was drawn at wherever on the image it stands, measured in the map's units.+ const ring = shapeRing(shape).map(toWorld);const center = meanPoint(ring);- const radius = ring.reduce((sum, point) => sum + Math.hypot(point[0] - center[0], point[1] - center[1]), 0) / ring.length;- return writeShape({ type: "circle", points: [ center.map(roundPixel) as [number, number] ], radius: roundPixel(radius) });+ return writeShape({+ type: "circle",+ points: [ center.map(round) as [number, number] ],+ radius: round(meanDistance(ring, center))+ });}- return writeShape({ type: shape.type, points: shape.coordinates.map(toPixel) });+ return writeShape({ type: shape.type, points: shape.coordinates.map(toStored) });}};}+/**+ * The corners a `#map:imageBounds` value names, as `x,y x,y` for the top-left and the bottom-right+ * corner, or `null` where it names none. Corners sharing an `x` or a `y` span nothing and name none.+ */+export function parseImageExtent(value: string | null | undefined): ImageExtent | null {+ const parts = value?.trim().split(/\s+/);+ if (parts?.length !== 2) return null;++ const topLeft = parsePair(parts[0]);+ const bottomRight = parsePair(parts[1]);+ if (!topLeft || !bottomRight || topLeft[0] === bottomRight[0] || topLeft[1] === bottomRight[1]) {+ return null;+ }++ return { topLeft, bottomRight };+}+/** `x,y` as an image label stores it, or `null` if unreadable. */-function parsePixel(value: string | null | undefined): [number, number] | null {+function parsePair(value: string | null | undefined): [number, number] | null {if (!value) return null;const [ x, y ] = value.split(",", 2).map((part) => parseFloat(part));@@ -233,12 +294,17 @@ function parsePixel(value: string | null | undefined): [number, number] | null {return [ x, y ];}-function roundPixel(value: number) {- return Number(value.toFixed(PIXEL_DECIMALS));+/** The decimals that resolve a step of `unit`, none for a step of one or more. */+function decimalsFor(unit: number) {+ return Math.max(0, Math.ceil(-Math.log10(unit)));}-/** A circle on the image as a ring of pixels, without the closing repeat. */-function pixelCircle([ x, y ]: [number, number], radius: number): [number, number][] {+function roundTo(value: number, decimals: number) {+ return Number(value.toFixed(decimals));+}++/** A circle in the map's coordinates as a ring, without the closing repeat. */+function worldCircle([ x, y ]: [number, number], radius: number): [number, number][] {const ring: [number, number][] = [];for (let i = 0; i < CIRCLE_SEGMENTS; i++) {const angle = (2 * Math.PI * i) / CIRCLE_SEGMENTS;@@ -247,6 +313,15 @@ function pixelCircle([ x, y ]: [number, number], radius: number): [number, numbereturn ring;}+function toMercator([ lng, lat ]: [number, number]): [number, number] {+ const { x, y } = MercatorCoordinate.fromLngLat({ lng, lat });+ return [ x, y ];+}++function meanDistance(points: [number, number][], [ cx, cy ]: [number, number]) {+ return points.reduce((sum, [ x, y ]) => sum + Math.hypot(x - cx, y - cy), 0) / points.length;+}+function meanPoint(points: [number, number][]): [number, number] {let x = 0;let y = 0;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.htmlindex b52e7dd2b1..8d8734cdaf 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@@ -1,8 +1,9 @@<p>An image map is a geo map drawn over an image of your own instead of aworld map, such as a floor plan, a fantasy map for a tabletop game, ora diagram to annotate. Markers and shapes work as they do on a geo map,- but their positions are measured in the image's own pixels instead of latitude- and longitude.</p>+ but their positions are measured on the image instead of in latitude and+ longitude: in the image's own pixels, or in a coordinate system of your+ choosing, such as the one a video game uses.</p><h2>Creating an image map</h2><ol><li>Upload the image as a note of its own, for example by dragging the file@@ -37,13 +38,35 @@ class="admonition note"><p>The look of the marker titles follows the image: if the image is dark,add the <code>#map:darkStyle</code> label to the geo map so that the titlesare drawn in a light color.</p>+<h2>Choosing the coordinate system</h2>+<p>By default, positions are measured in pixels of the image at its original+ size, from its top-left corner, with <code>x</code> growing to the right+ and <code>y</code> growing downwards.</p>+<p>To use coordinates of your own instead, add a <code>#map:imageBounds</code> label+ to the geo map, naming the coordinates of the image's top-left corner and+ of its bottom-right corner as <code>x,y x,y</code>, with a space between+ the two corners. All positions are then read and written in those coordinates,+ including the ones shown in the contextual menu and in the popup view.+ For example:</p>+<ul>+ <li>A screenshot of a game map that covers <code>x</code> from -512 to 512 and <code>y</code> from+ -512 to 512, with <code>y</code> growing downwards: <code>#map:imageBounds=-512,-512 512,512</code>.+ Coordinates copied from the game can then be pasted directly into <code>#imagePosition</code>.</li>+ <li>A world whose <code>y</code> grows upwards, with the origin in the middle+ of the image: <code>#map:imageBounds=-2000,1000 2000,-1000</code>. A top-left <code>y</code> larger+ than the bottom-right one is what flips the axis.</li>+ <li>A floor plan measured in meters: <code>#map:imageBounds=0,0 24,12</code>.</li>+</ul>+<p>The two axes don't have to use the same scale. A circle is always measured+ in the map's own units, so it appears as an ellipse when the units are+ 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>How the positions are stored</h2>-<p>Positions are stored in pixels of the image at its original size, measured- from its top-left corner, with <code>x</code> growing to the right and <code>y</code> growing- downwards. Because they 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>-<figure class="table">+<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>+<figure+class="table"><table><thead><tr>@@ -62,14 +85,19 @@ class="admonition note"></td><td>A shape, in the same format as <code>#geoShape</code> (see <a class="reference-link"href="#root/_help_C2H9HK4BzwG7">Drawing shapes</a>) but with <code>x,y</code> pairs,- and a circle's radius in pixels, for example <code>#imageShape=circle:400,300 50</code>.</td>+ and a circle's radius in the map's units, for example <code>#imageShape=circle:400,300 50</code>.</td></tr></tbody></table></figure>-<p>Since the positions are in pixels, replacing the image with one of a different- size moves the markers relative to what the image shows. Prefer keeping- the same dimensions when updating the image.</p>+<p>The positions belong to the coordinate system, not to the image. When+ replacing the image with a different one, for example a higher-resolution+ copy, keep <code>#map:imageBounds</code> describing the area the new image+ covers and every marker stays in place. Without <code>#map:imageBounds</code>,+ the positions are pixels, so an image of a different size moves the markers+ relative to what the image shows; to avoid that, set <code>#map:imageBounds</code> to+ the size of the old image (<code>0,0 <width>,<height></code>)+ before replacing it.</p><aside class="admonition tip"><p>To draw freely over an image instead of placing notes on it, considera <a class="reference-link" href="#root/_help_grjYqerjn243">Canvas</a>.</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.mdindex 613fb45862..94a73ea223 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@@ -1,5 +1,5 @@# Image maps-An image map is a geo map drawn over an image of your own instead of a world map, such as a floor plan, a fantasy map for a tabletop game, or a diagram to annotate. Markers and shapes work as they do on a geo map, but their positions are measured in the image's own pixels instead of latitude and longitude.+An image map is a geo map drawn over an image of your own instead of a world map, such as a floor plan, a fantasy map for a tabletop game, or a diagram to annotate. Markers and shapes work as they do on a geo map, but their positions are measured on the image instead of in latitude and longitude: in the image's own pixels, or in a coordinate system of your choosing, such as the one a video game uses.## Creating an image map@@ -27,16 +27,30 @@ The features that only make sense on a real map are not available on an image maThe 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.+## Choosing the coordinate system++By default, positions are measured in pixels of the image at its original size, from its top-left corner, with `x` growing to the right and `y` growing downwards.++To use coordinates of your own instead, add a `#map:imageBounds` label to the geo map, naming the coordinates of the image's top-left corner and of its bottom-right corner as `x,y x,y`, with a space between the two corners. All positions are then read and written in those coordinates, including the ones shown in the contextual menu and in the popup view. For example:++* A screenshot of a game map that covers `x` from -512 to 512 and `y` from -512 to 512, with `y` growing downwards: `#map:imageBounds=-512,-512 512,512`. Coordinates copied from the game can then be pasted directly into `#imagePosition`.+* A world whose `y` grows upwards, with the origin in the middle of the image: `#map:imageBounds=-2000,1000 2000,-1000`. A top-left `y` larger than the bottom-right one is what flips the axis.+* A floor plan measured in meters: `#map:imageBounds=0,0 24,12`.++The two axes don't have to use the same scale. A circle is always measured in the map's own units, so it appears as an ellipse when the units are stretched differently along the two axes.++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.+## How the positions are stored-Positions are stored in pixels of the image at its original size, measured from its top-left corner, with `x` growing to the right and `y` growing downwards. Because they 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.+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.| Label | Content || --- | --- || `#imagePosition` | The position of a marker, as `x,y`, for example `#imagePosition=320,145`. |-| `#imageShape` | A shape, in the same format as `#geoShape` (see <a class="reference-link" href="Drawing%20shapes.md">Drawing shapes</a>) but with `x,y` pairs, and a circle's radius in pixels, for example `#imageShape=circle:400,300 50`. |+| `#imageShape` | A shape, in the same format as `#geoShape` (see <a class="reference-link" href="Drawing%20shapes.md">Drawing shapes</a>) but with `x,y` pairs, and a circle's radius in the map's units, for example `#imageShape=circle:400,300 50`. |-Since the positions are in pixels, replacing the image with one of a different size moves the markers relative to what the image shows. Prefer keeping the same dimensions when updating the image.+The positions belong to the coordinate system, not to the image. When replacing the image with a different one, for example a higher-resolution copy, keep `#map:imageBounds` describing the area the new image covers and every marker stays in place. Without `#map:imageBounds`, the positions are pixels, so an image of a different size moves the markers relative to what the image shows; to avoid that, set `#map:imageBounds` to the size of the old image (`0,0 <width>,<height>`) before replacing it.> [!TIP]> To draw freely over an image instead of placing notes on it, consider a <a class="reference-link" href="../../Note%20Types/Canvas.md">Canvas</a>.\ No newline at end of filediff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.tsindex c1c9e8fea2..a8f20c70d5 100644--- a/packages/commons/src/lib/builtin_attributes.ts+++ b/packages/commons/src/lib/builtin_attributes.ts@@ -302,9 +302,11 @@ const BUILTIN_ATTRIBUTES = [// client's geomap/shapes.ts).{ type: "label", name: "geoShape", valueType: "text", hasUserValue: true },// The counterparts of `geolocation` and `geoShape` on a map drawn over an image (`~map:image`):- // `x,y` in the image's own pixels, measured from its top-left corner.+ // `x,y` in the map's coordinates, which are the image's own pixels unless the map names others.{ type: "label", name: "imagePosition", valueType: "text", hasUserValue: true },{ type: "label", name: "imageShape", valueType: "text", hasUserValue: true },+ // The coordinates of an image map's top-left and bottom-right corners, as `x,y x,y`.+ { type: "label", name: "map:imageBounds", valueType: "text", hasUserValue: true },// Which note map a note map note draws; anything but `tree` is read as `link`.{ type: "label", name: "mapType", valueType: "select", hasUserValue: true, selectOptions: ["link", "tree"