Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): circle drawing tool, stored as a centre and a reach

Claude6f9e562ecb9e
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index ce2b9365b1..b495b56dc8 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -754,7 +754,7 @@
"end_time": "The time an event ends at, read against <code>#endDate</code> where there is one and <code>#startDate</code> otherwise.",
"recurrence": "A CalDAV <code>RRULE</code> string making the event repeat. The start is taken from <code>#startDate</code> and <code>#startTime</code>, so the rule leaves <code>DTSTART</code> out.",
"geolocation": "The latitude and longitude the note is placed at on a geo map.",
- "geo_shape": "A shape the note is drawn as on a geo map: the kind of shape, then the latitude and longitude of each point, e.g. <code>line:48.85,2.29 48.86,2.35</code>.",
+ "geo_shape": "A shape the note is drawn as on a geo map: the kind of shape, then the latitude and longitude of each point, e.g. <code>line:48.85,2.29 48.86,2.35</code> — or a circle as its centre and reach in metres, <code>circle:48.85,2.29 500</code>.",
"map_type": "Which note map is drawn: <code>link</code> for the relations between notes, or <code>tree</code> for the hierarchy.",
"map_style": "Which style a geo map is drawn in, chosen from the raster and vector styles offered in the collection properties.",
"map_dark_style": "Tells a geo map that the custom style given in <code>map:style</code> is a dark one, so that the marker titles are drawn light over it. The styles offered in the collection properties say so for themselves and need no such label.",
@@ -2862,6 +2862,9 @@
"draw-rectangle": "Draw a rectangle on the map",
"draw-rectangle-toast-title": "Draw a rectangle",
"draw-rectangle-instruction": "Click on the map at one corner, then click again at the opposite corner. Press Escape to cancel.",
+ "draw-circle": "Draw a circle on the map",
+ "draw-circle-toast-title": "Draw a circle",
+ "draw-circle-instruction": "Click on the map at the centre, then click again at the distance the circle should reach. Press Escape to cancel.",
"move-marker-instruction": "Click on the map to move the marker to that location or press Escape to dismiss.",
"move-marker-toast-title": "Move marker",
"unable-to-load-map": "Unable to load map.",
diff --git a/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx b/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx
index e3acb8df77..1e6ed634fb 100644
--- a/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/DrawShape.spec.tsx
@@ -42,7 +42,8 @@ vi.mock("terra-draw", () => {
TerraDraw,
TerraDrawLineStringMode: class { mode = "linestring"; },
TerraDrawPolygonMode: class { mode = "polygon"; },
- TerraDrawRectangleMode: class { mode = "rectangle"; }
+ TerraDrawRectangleMode: class { mode = "rectangle"; },
+ TerraDrawCircleMode: class { mode = "circle"; }
};
});
@@ -64,11 +65,18 @@ function instances(): FakeTerraDraw[] {
}
const LINE_FEATURE = {
+ properties: {},
geometry: { type: "LineString", coordinates: [ [ 1, 2 ], [ 3, 4 ] ] }
};
const RING_FEATURE = {
+ properties: {},
geometry: { type: "Polygon", coordinates: [ [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ], [ 1, 2 ] ] ] }
};
+/** A circle as Terra Draw finishes one: a ring around (10, 20), its radius in the properties. */
+const CIRCLE_FEATURE = {
+ properties: { mode: "circle", radiusKilometers: 0.5 },
+ geometry: { type: "Polygon", coordinates: [ [ [ 10, 21 ], [ 11, 20 ], [ 10, 19 ], [ 9, 20 ], [ 10, 21 ] ] ] }
+};
describe("DrawShape", () => {
let container: HTMLElement;
@@ -139,6 +147,14 @@ describe("DrawShape", () => {
expect(onFinish).toHaveBeenCalledWith({ type: "polygon", coordinates: [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] });
});
+ it("hands a finished circle over as its centre and reach, read back out of the ring", () => {
+ renderSession("circle");
+
+ expect(instances()[0].modeName).toBe("circle");
+ act(() => instances()[0].finish("f1", "draw", CIRCLE_FEATURE));
+ expect(onFinish).toHaveBeenCalledWith({ type: "circle", center: [ 10, 20 ], radiusMeters: 500 });
+ });
+
it("leaves alone what is not a drawing being finished", () => {
renderSession("line");
@@ -157,6 +173,13 @@ describe("shapeFromFeature", () => {
});
it("survives a polygon with no ring at all", () => {
- expect(shapeFromFeature("polygon", { geometry: { type: "Polygon", coordinates: [] } } as never)).toBeNull();
+ expect(shapeFromFeature("polygon", { properties: {}, geometry: { type: "Polygon", coordinates: [] } } as never)).toBeNull();
+ });
+
+ it("refuses a circle whose radius the properties do not carry", () => {
+ expect(shapeFromFeature("circle", {
+ ...CIRCLE_FEATURE,
+ properties: { mode: "circle" }
+ } as never)).toBeNull();
});
});
diff --git a/apps/client/src/widgets/collections/geomap/DrawShape.tsx b/apps/client/src/widgets/collections/geomap/DrawShape.tsx
index e804c49879..1ca361e93d 100644
--- a/apps/client/src/widgets/collections/geomap/DrawShape.tsx
+++ b/apps/client/src/widgets/collections/geomap/DrawShape.tsx
@@ -1,12 +1,12 @@
import { useContext, useEffect, useRef } from "preact/hooks";
-import { type GeoJSONStoreFeatures, TerraDraw, TerraDrawLineStringMode, TerraDrawPolygonMode, TerraDrawRectangleMode } from "terra-draw";
+import { type GeoJSONStoreFeatures, TerraDraw, TerraDrawCircleMode, TerraDrawLineStringMode, TerraDrawPolygonMode, TerraDrawRectangleMode } from "terra-draw";
import { TerraDrawMapLibreGLAdapter } from "terra-draw-maplibre-gl-adapter";
import { MapStyleLoaded, ParentMap } from "./map";
-import { type GeoShape, polygonFromRing } from "./shapes";
+import { type GeoShape, polygonFromRing, ringCenter } from "./shapes";
/** The drawing tools on offer, each arming Terra Draw with a mode of its own. */
-export type DrawTool = "line" | "polygon" | "rectangle";
+export type DrawTool = "line" | "polygon" | "rectangle" | "circle";
interface DrawShapeProps {
tool: DrawTool;
@@ -78,6 +78,8 @@ function buildMode(tool: DrawTool) {
return new TerraDrawPolygonMode();
case "rectangle":
return new TerraDrawRectangleMode();
+ case "circle":
+ return new TerraDrawCircleMode();
}
}
@@ -87,7 +89,9 @@ function buildMode(tool: DrawTool) {
*
* Every area tool comes through the polygon branch: whatever hand movement made it, what was made
* is a ring, and a ring is a polygon note (with its closing repeat left behind — the label does
- * not spell it; see shapes.ts).
+ * not spell it; see shapes.ts). The circle alone is read back out of its ring: Terra Draw draws
+ * one as a many-cornered polygon carrying its radius in the properties, and the note stores what
+ * the drawing meant — a centre and a reach — rather than the ring that approximated it.
*/
export function shapeFromFeature(tool: DrawTool, feature: GeoJSONStoreFeatures): GeoShape | null {
if (tool === "line") {
@@ -98,5 +102,14 @@ export function shapeFromFeature(tool: DrawTool, feature: GeoJSONStoreFeatures):
if (feature.geometry.type !== "Polygon") return null;
const ring = feature.geometry.coordinates[0] as [number, number][] | undefined;
- return ring ? polygonFromRing(ring) : null;
+ if (!ring) return null;
+
+ if (tool === "circle") {
+ const radiusKilometers = Number(feature.properties.radiusKilometers);
+ const center = ringCenter(polygonFromRing(ring).coordinates);
+ if (!center || !Number.isFinite(radiusKilometers) || radiusKilometers <= 0) return null;
+ return { type: "circle", center, radiusMeters: radiusKilometers * 1000 };
+ }
+
+ return polygonFromRing(ring);
}
diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
index 625e529b19..8e9f6f1860 100644
--- a/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.spec.tsx
@@ -44,7 +44,8 @@ function renderBar({ map = {} as never, isReadOnly = false, placing = false, dra
const DRAW_TOOL_ICONS: { tool: DrawTool; icon: string }[] = [
{ tool: "line", icon: "bx-vector" },
{ tool: "polygon", icon: "bx-shape-polygon" },
- { tool: "rectangle", icon: "bx-rectangle" }
+ { tool: "rectangle", icon: "bx-rectangle" },
+ { tool: "circle", icon: "bx-shape-circle" }
];
describe("geo map EditToolbar", () => {
diff --git a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
index 133f980821..ba28628ea7 100644
--- a/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
+++ b/apps/client/src/widgets/collections/geomap/EditToolbar.tsx
@@ -28,7 +28,8 @@ interface EditToolbarProps {
const DRAW_TOOLS: { tool: DrawTool; icon: string; title: () => string }[] = [
{ tool: "line", icon: "bx-vector", title: () => t("geo-map.draw-line") },
{ tool: "polygon", icon: "bx-shape-polygon", title: () => t("geo-map.draw-polygon") },
- { tool: "rectangle", icon: "bx-rectangle", title: () => t("geo-map.draw-rectangle") }
+ { tool: "rectangle", icon: "bx-rectangle", title: () => t("geo-map.draw-rectangle") },
+ { tool: "circle", icon: "bx-shape-circle", title: () => t("geo-map.draw-circle") }
];
/**
diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx
index fc46770394..aae17db515 100644
--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.spec.tsx
@@ -141,6 +141,22 @@ describe("ShapeLayer", () => {
expect(map.layers.size).toBe(0);
});
+ it("draws a circle as the ring its two numbers walk out, worn like any other area", () => {
+ map.loadStyle();
+ renderShape({ type: "circle", center: [ 2.29, 48.85 ], radiusMeters: 500 });
+
+ const source = map.sources.get(shapeSourceId(NOTE_ID)) as {
+ data: { geometry: { type: string; coordinates: [number, number][][] } };
+ };
+ expect(source.data.geometry.type).toBe("Polygon");
+ const ring = source.data.geometry.coordinates[0];
+ // The generated ring, closed back up: sixty-four corners and the closing repeat.
+ expect(ring).toHaveLength(65);
+ expect(ring[0]).toEqual(ring[ring.length - 1]);
+ expect(map.layers.has(`shape-fill-${NOTE_ID}`)).toBe(true);
+ expect(map.layers.has(`shape-stroke-${NOTE_ID}`)).toBe(true);
+ });
+
it("waits for the style, and is put back when a style switch wipes the map", () => {
// Mounted before the style has loaded — as a shape whose note arrives early always is —
// nothing can go on yet.
diff --git a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx
index 3f501c2bbc..20a8810248 100644
--- a/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx
+++ b/apps/client/src/widgets/collections/geomap/ShapeLayer.tsx
@@ -1,7 +1,7 @@
import { useContext, useEffect } from "preact/hooks";
import { MapStyleLoaded, ParentMap } from "./map";
-import { closeRing, type GeoShape } from "./shapes";
+import { circleRing, closeRing, type GeoShape, serializeGeoShape } from "./shapes";
interface ShapeLayerProps {
/** The note the shape belongs to, which is what its source and layers are named after. */
@@ -28,7 +28,8 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {
// The shape as a dependency the effect can compare: the object is rebuilt on every parse of
// the label, so handing it over as-is would tear the layers down and put them back per render.
- const shapeKey = `${shape.type}:${shape.coordinates.flat().join(",")}`;
+ // Its label spelling is exactly such a comparison — one string, stable across parses.
+ const shapeKey = serializeGeoShape(shape);
useEffect(() => {
if (!parentMap) return;
@@ -54,7 +55,13 @@ export function ShapeLayer({ noteId, shape, color }: ShapeLayerProps) {
properties: { id: noteId },
geometry: shape.type === "line"
? { type: "LineString", coordinates: shape.coordinates }
- : { type: "Polygon", coordinates: [ closeRing(shape.coordinates) ] }
+ // An area is its ring closed back up — the ring the label spells
+ // for a polygon, or the one walked out of a circle's two numbers.
+ : { type: "Polygon", coordinates: [ closeRing(
+ shape.type === "circle"
+ ? circleRing(shape.center, shape.radiusMeters)
+ : shape.coordinates
+ ) ] }
}
});
}
diff --git a/apps/client/src/widgets/collections/geomap/api.ts b/apps/client/src/widgets/collections/geomap/api.ts
index ae50eaec49..37058fe4fb 100644
--- a/apps/client/src/widgets/collections/geomap/api.ts
+++ b/apps/client/src/widgets/collections/geomap/api.ts
@@ -15,7 +15,8 @@ export const CHILD_NOTE_ICON = "bx bx-pin";
/** The icon a shape note wears, by the kind of shape its label spells. */
export const SHAPE_NOTE_ICONS = {
line: "bx bx-vector",
- polygon: "bx bx-shape-polygon"
+ polygon: "bx bx-shape-polygon",
+ circle: "bx bx-shape-circle"
} as const satisfies Record<GeoShape["type"], string>;
export async function moveMarker(noteId: string, latLng: { lat: number; lng: number } | null) {
diff --git a/apps/client/src/widgets/collections/geomap/index.tsx b/apps/client/src/widgets/collections/geomap/index.tsx
index 6e895159ac..ad44ae9169 100644
--- a/apps/client/src/widgets/collections/geomap/index.tsx
+++ b/apps/client/src/widgets/collections/geomap/index.tsx
@@ -459,6 +459,12 @@ function drawingToast(tool: DrawTool): { icon: string; title: string; message: s
title: t("geo-map.draw-rectangle-toast-title"),
message: t("geo-map.draw-rectangle-instruction")
};
+ case "circle":
+ return {
+ icon: "shape-circle",
+ title: t("geo-map.draw-circle-toast-title"),
+ message: t("geo-map.draw-circle-instruction")
+ };
}
}
diff --git a/apps/client/src/widgets/collections/geomap/shapes.spec.ts b/apps/client/src/widgets/collections/geomap/shapes.spec.ts
index 79bc176713..676110273e 100644
--- a/apps/client/src/widgets/collections/geomap/shapes.spec.ts
+++ b/apps/client/src/widgets/collections/geomap/shapes.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { closeRing, parseGeoShape, polygonFromRing, serializeGeoShape } from "./shapes";
+import { circleRing, closeRing, parseGeoShape, polygonFromRing, ringCenter, serializeGeoShape } from "./shapes";
describe("serializeGeoShape", () => {
it("writes lat,lng pairs behind the kind's prefix, rounded but not padded", () => {
@@ -18,6 +18,14 @@ describe("serializeGeoShape", () => {
})).toBe("polygon:2,1 4,3 6,5");
});
+ it("writes a circle as its centre and its reach, not the ring that would approximate it", () => {
+ expect(serializeGeoShape({
+ type: "circle",
+ center: [ 2.2946944444, 48.8580925 ],
+ radiusMeters: 512.3456
+ })).toBe("circle:48.858093,2.294694 512.3");
+ });
+
it("round-trips through parseGeoShape", () => {
const coordinates: [number, number][] = [
[ 13.404954, 52.520008 ],
@@ -27,6 +35,9 @@ describe("serializeGeoShape", () => {
for (const type of [ "line", "polygon" ] as const) {
expect(parseGeoShape(serializeGeoShape({ type, coordinates }))).toEqual({ type, coordinates });
}
+
+ const circle = { type: "circle", center: [ 13.404954, 52.520008 ], radiusMeters: 500 } as const;
+ expect(parseGeoShape(serializeGeoShape(circle))).toEqual(circle);
});
});
@@ -62,6 +73,19 @@ describe("parseGeoShape", () => {
expect(parseGeoShape("polygon:1,2 3,4")).toBeNull();
expect(parseGeoShape("polygon:1,2 3,4 5,6")).not.toBeNull();
});
+
+ it("holds a circle to a centre and a positive reach", () => {
+ expect(parseGeoShape("circle:48.85,2.29 500")).toEqual({
+ type: "circle",
+ center: [ 2.29, 48.85 ],
+ radiusMeters: 500
+ });
+ // No radius, two centres, a reach of nothing, and one of nonsense.
+ expect(parseGeoShape("circle:48.85,2.29")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 48.86,2.35 500")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 0")).toBeNull();
+ expect(parseGeoShape("circle:48.85,2.29 far")).toBeNull();
+ });
});
describe("rings", () => {
@@ -77,5 +101,34 @@ describe("rings", () => {
it("survives a ring with nothing in it", () => {
expect(polygonFromRing([]).coordinates).toEqual([]);
+ expect(ringCenter([])).toBeNull();
+ });
+
+ it("walks a circle out as a ring of points its reach away from the centre", () => {
+ const center: [number, number] = [ 2.294694, 48.858093 ];
+ const radiusMeters = 500;
+ const ring = circleRing(center, radiusMeters);
+
+ expect(ring).toHaveLength(64);
+ // Not closed — the closing repeat is closeRing's to add, as for any other ring.
+ expect(ring[0]).not.toEqual(ring[ring.length - 1]);
+ // Every point stands the same distance out, give or take the arithmetic.
+ for (const point of ring) {
+ expect(haversineMeters(center, point)).toBeCloseTo(radiusMeters, 0);
+ }
+ // And the ring stands around where it was asked to.
+ const [ lng, lat ] = ringCenter(ring) ?? [ NaN, NaN ];
+ expect(lng).toBeCloseTo(center[0], 4);
+ expect(lat).toBeCloseTo(center[1], 4);
});
});
+
+/** The distance between two points the way the ring generator must honour it: over the sphere. */
+function haversineMeters([ lng1, lat1 ]: [number, number], [ lng2, lat2 ]: [number, number]): number {
+ const toRad = (d: number) => (d * Math.PI) / 180;
+ const dLat = toRad(lat2 - lat1);
+ const dLng = toRad(lng2 - lng1);
+ const a = Math.sin(dLat / 2) ** 2 +
+ Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;
+ return 6371008.8 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
+}
diff --git a/apps/client/src/widgets/collections/geomap/shapes.ts b/apps/client/src/widgets/collections/geomap/shapes.ts
index 6d91097f7e..38f6311766 100644
--- a/apps/client/src/widgets/collections/geomap/shapes.ts
+++ b/apps/client/src/widgets/collections/geomap/shapes.ts
@@ -35,17 +35,35 @@ export interface GeoShapePolygon {
coordinates: [number, number][];
}
+export interface GeoShapeCircle {
+ type: "circle";
+ /** `[lng, lat]` of the centre. */
+ center: [number, number];
+ /** How far the circle reaches, in metres — the one number the points would only approximate. */
+ radiusMeters: number;
+}
+
/** Every kind of shape a note can carry. */
-export type GeoShape = GeoShapeLine | GeoShapePolygon;
+export type GeoShape = GeoShapeLine | GeoShapePolygon | GeoShapeCircle;
-/** The fewest points each kind is a shape at all with: one point is no line, and two no area. */
+/** The fewest points each point-list kind is a shape at all with: one point is no line, and two
+ * no area. A circle is not among them — it is a centre and a reach, not a walk. */
const MINIMUM_POINTS = { line: 2, polygon: 3 } as const;
/**
* A shape as its label value: the kind, a colon, and each point as `lat,lng` — the order the
- * reader of a `#geolocation` label expects, however the coordinates are held in memory.
+ * reader of a `#geolocation` label expects, however the coordinates are held in memory. A circle
+ * is its centre and then its radius in metres, `circle:48.85,2.29 500`, rather than the ring of
+ * points a drawing library holds it as: the ring is an approximation regenerated at whatever
+ * fineness the reader wants (see {@link circleRing}), and sixty-odd points would swell the label
+ * for less information than two numbers carry.
*/
export function serializeGeoShape(shape: GeoShape): string {
+ if (shape.type === "circle") {
+ const [ lng, lat ] = shape.center;
+ return `circle:${round(lat)},${round(lng)} ${Math.round(shape.radiusMeters * 10) / 10}`;
+ }
+
return `${shape.type}:${serializePoints(shape.coordinates)}`;
}
@@ -62,14 +80,33 @@ export function parseGeoShape(value: string): GeoShape | null {
if (divide < 0) return null;
const type = value.slice(0, divide);
+ const rest = value.slice(divide + 1);
+
+ if (type === "circle") {
+ return parseCircle(rest);
+ }
+
if (!isPointKind(type)) return null;
- const coordinates = parsePoints(value.slice(divide + 1));
+ const coordinates = parsePoints(rest);
if (!coordinates || coordinates.length < MINIMUM_POINTS[type]) return null;
return { type, coordinates };
}
+function parseCircle(rest: string): GeoShapeCircle | null {
+ const parts = rest.trim().split(/\s+/);
+ if (parts.length !== 2) return null;
+
+ const center = parsePoints(parts[0]);
+ const radiusMeters = Number(parts[1]);
+ if (!center || center.length !== 1 || !Number.isFinite(radiusMeters) || radiusMeters <= 0) {
+ return null;
+ }
+
+ return { type: "circle", center: center[0], radiusMeters };
+}
+
/**
* A polygon from the ring a drawing tool hands over, which spells the closing point out — GeoJSON
* rings end where they began, and the label does not (see the module note).
@@ -86,6 +123,65 @@ export function closeRing(coordinates: [number, number][]): [number, number][] {
return [ ...coordinates, coordinates[0] ];
}
+/** The mean of the earth's radii, as MapLibre also takes it. */
+const EARTH_RADIUS_METERS = 6371008.8;
+
+/** How many corners a circle's ring is drawn with — enough that nobody sees them. */
+const CIRCLE_SEGMENTS = 64;
+
+/**
+ * A circle's reach walked out as a ring, one point per bearing, without the closing repeat — the
+ * ring a circle label is drawn from (see {@link serializeGeoShape} for why it is not stored).
+ * Great-circle rather than flat arithmetic, so a wide circle far from the equator keeps its shape.
+ */
+export function circleRing(center: [number, number], radiusMeters: number, segments = CIRCLE_SEGMENTS): [number, number][] {
+ const [ lng, lat ] = center;
+ const angular = radiusMeters / EARTH_RADIUS_METERS;
+ const latRad = toRadians(lat);
+ const lngRad = toRadians(lng);
+
+ const ring: [number, number][] = [];
+ for (let i = 0; i < segments; i++) {
+ const bearing = (2 * Math.PI * i) / segments;
+ const pointLat = Math.asin(
+ Math.sin(latRad) * Math.cos(angular) +
+ Math.cos(latRad) * Math.sin(angular) * Math.cos(bearing)
+ );
+ const pointLng = lngRad + Math.atan2(
+ Math.sin(bearing) * Math.sin(angular) * Math.cos(latRad),
+ Math.cos(angular) - Math.sin(latRad) * Math.sin(pointLat)
+ );
+ ring.push([ toDegrees(pointLng), toDegrees(pointLat) ]);
+ }
+
+ return ring;
+}
+
+/**
+ * Where a ring stands: the mean of its points. Exact for the regular ring a circle tool hands
+ * over, which is all it is asked about — this is how the centre a circle label stores is read
+ * back off the ring Terra Draw drew (see `shapeFromFeature`).
+ */
+export function ringCenter(ring: [number, number][]): [number, number] | null {
+ if (ring.length === 0) return null;
+
+ let lngSum = 0;
+ let latSum = 0;
+ for (const [ lng, lat ] of ring) {
+ lngSum += lng;
+ latSum += lat;
+ }
+ return [ lngSum / ring.length, latSum / ring.length ];
+}
+
+function toRadians(degrees: number): number {
+ return (degrees * Math.PI) / 180;
+}
+
+function toDegrees(radians: number): number {
+ return (radians * 180) / Math.PI;
+}
+
function isPointKind(type: string): type is keyof typeof MINIMUM_POINTS {
return Object.hasOwn(MINIMUM_POINTS, type);
}