@mark1russell7/cartography 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/dist/index.d.ts +434 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1062 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1062 @@
|
|
|
1
|
+
import { bboxOfPoints, geodesicDirect, locatePoint, simplifyRegions } from "@mark1russell7/geo";
|
|
2
|
+
import { escapeAttribute, escapeHtml } from "@mark1russell7/text";
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
/** The error that each function of this package throws for an incorrect map. */
|
|
5
|
+
var MapError = class extends Error {
|
|
6
|
+
/** The reason of the refusal. */
|
|
7
|
+
code;
|
|
8
|
+
/**
|
|
9
|
+
* @param code - The reason of the refusal.
|
|
10
|
+
* @param message - The text for a person.
|
|
11
|
+
*/
|
|
12
|
+
constructor(code, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "MapError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
// src/filter.ts
|
|
19
|
+
/** This function gives the kind of a geometry. */
|
|
20
|
+
function geometryKind(geometry) {
|
|
21
|
+
switch (geometry.type) {
|
|
22
|
+
case "Point":
|
|
23
|
+
case "MultiPoint": return "point";
|
|
24
|
+
case "LineString":
|
|
25
|
+
case "MultiLineString": return "line";
|
|
26
|
+
case "Polygon":
|
|
27
|
+
case "MultiPolygon": return "area";
|
|
28
|
+
case "GeometryCollection": {
|
|
29
|
+
const kinds = new Set(geometry.geometries.map(geometryKind));
|
|
30
|
+
return kinds.size === 1 ? [...kinds][0] : "mixed";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** This function tells if a feature matches a filter. A feature with no geometry matches no `{ geometry }` filter. */
|
|
35
|
+
function matchesFilter(filter, feature) {
|
|
36
|
+
if ("all" in filter) return filter.all.every((item) => matchesFilter(item, feature));
|
|
37
|
+
if ("any" in filter) return filter.any.some((item) => matchesFilter(item, feature));
|
|
38
|
+
if ("not" in filter) return !matchesFilter(filter.not, feature);
|
|
39
|
+
if ("geometry" in filter) return feature.geometry !== null && geometryKind(feature.geometry) === filter.geometry;
|
|
40
|
+
const properties = feature.properties ?? {};
|
|
41
|
+
const has = Object.hasOwn(properties, filter.property);
|
|
42
|
+
if ("exists" in filter) return has === filter.exists;
|
|
43
|
+
return has && filter.in.includes(properties[filter.property]);
|
|
44
|
+
}
|
|
45
|
+
const KINDS = [
|
|
46
|
+
"point",
|
|
47
|
+
"line",
|
|
48
|
+
"area",
|
|
49
|
+
"mixed"
|
|
50
|
+
];
|
|
51
|
+
/**
|
|
52
|
+
* This function refuses a value that is not a `Filter`, for example a filter from JSON.
|
|
53
|
+
*
|
|
54
|
+
* @throws MapError - The code is `filter`.
|
|
55
|
+
*/
|
|
56
|
+
function checkFilter(filter, path = "filter") {
|
|
57
|
+
const fail = (reason) => {
|
|
58
|
+
throw new MapError("filter", `${path}: ${reason}`);
|
|
59
|
+
};
|
|
60
|
+
if (typeof filter !== "object" || filter === null || Array.isArray(filter)) fail("a filter must be an object");
|
|
61
|
+
const value = filter;
|
|
62
|
+
const keys = Object.keys(value).toSorted().join(",");
|
|
63
|
+
if (keys === "all" || keys === "any") {
|
|
64
|
+
const items = value[keys];
|
|
65
|
+
if (!Array.isArray(items)) fail(`the member ${keys} must be an array`);
|
|
66
|
+
items.forEach((item, i) => checkFilter(item, `${path}.${keys}[${i}]`));
|
|
67
|
+
} else if (keys === "not") checkFilter(value["not"], `${path}.not`);
|
|
68
|
+
else if (keys === "geometry") {
|
|
69
|
+
if (!KINDS.includes(value["geometry"])) fail(`the geometry must be one of ${KINDS.join(", ")}`);
|
|
70
|
+
} else if (keys === "in,property" || keys === "exists,property") {
|
|
71
|
+
if (typeof value["property"] !== "string") fail("the property must be a string");
|
|
72
|
+
if (keys === "exists,property" && typeof value["exists"] !== "boolean") fail("the member exists must be true or false");
|
|
73
|
+
if (keys === "in,property") {
|
|
74
|
+
const items = value["in"];
|
|
75
|
+
if (!Array.isArray(items) || !items.every((item) => [
|
|
76
|
+
"string",
|
|
77
|
+
"number",
|
|
78
|
+
"boolean"
|
|
79
|
+
].includes(typeof item))) fail("the member in must be an array of strings, numbers and booleans");
|
|
80
|
+
}
|
|
81
|
+
} else fail(`the members ${keys === "" ? "(none)" : keys} are not a form of a filter`);
|
|
82
|
+
}
|
|
83
|
+
// src/frame.ts
|
|
84
|
+
/**
|
|
85
|
+
* The frame of a map: the part of the Earth that the map shows, its scale and its size on the paper.
|
|
86
|
+
*
|
|
87
|
+
* @packageDocumentation
|
|
88
|
+
*/
|
|
89
|
+
/** This function refuses a frame with a scale or a size that is not a finite number more than 0. */
|
|
90
|
+
function checkFrame(frame) {
|
|
91
|
+
for (const [name, value] of [
|
|
92
|
+
["scale", frame.scale],
|
|
93
|
+
["width", frame.widthMm],
|
|
94
|
+
["height", frame.heightMm]
|
|
95
|
+
]) if (!(Number.isFinite(value) && value > 0)) throw new MapError("frame", `The ${name} ${value} of the frame is not a finite number more than 0`);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* This function gives the functions of a frame between the Earth and the paper.
|
|
99
|
+
*
|
|
100
|
+
* - The scale of the frame is the true scale at the center. The function divides by the scale factor of the projection
|
|
101
|
+
* at the center: the square root of `max * min` of `projection.scale`.
|
|
102
|
+
* - For Web Mercator, the scale changes with the latitude. For `azimuthalEquidistant`, it is almost the same on all
|
|
103
|
+
* the map.
|
|
104
|
+
*
|
|
105
|
+
* @throws MapError - The code is `frame`.
|
|
106
|
+
* @throws GeoError - The center is not a correct point for the projection.
|
|
107
|
+
*/
|
|
108
|
+
function frameView(frame) {
|
|
109
|
+
checkFrame(frame);
|
|
110
|
+
const { projection, center } = frame;
|
|
111
|
+
const factors = projection.scale(center);
|
|
112
|
+
const mmPerMeter = 1e3 / frame.scale;
|
|
113
|
+
const mmPerPlaneMeter = mmPerMeter / Math.sqrt(factors.max * factors.min);
|
|
114
|
+
const origin = projection.toPlane(center);
|
|
115
|
+
const middleX = frame.widthMm / 2;
|
|
116
|
+
const middleY = frame.heightMm / 2;
|
|
117
|
+
const toPaper = (point) => {
|
|
118
|
+
const plane = projection.toPlane(point);
|
|
119
|
+
return {
|
|
120
|
+
x: middleX + (plane.x - origin.x) * mmPerPlaneMeter,
|
|
121
|
+
y: middleY - (plane.y - origin.y) * mmPerPlaneMeter
|
|
122
|
+
};
|
|
123
|
+
};
|
|
124
|
+
const fromPaper = (point) => projection.fromPlane({
|
|
125
|
+
x: origin.x + (point.x - middleX) / mmPerPlaneMeter,
|
|
126
|
+
y: origin.y - (point.y - middleY) / mmPerPlaneMeter
|
|
127
|
+
});
|
|
128
|
+
const north = toPaper(geodesicDirect(center, 0, 1 / mmPerMeter).point);
|
|
129
|
+
const northDegrees = Math.atan2(north.x - middleX, middleY - north.y) * 180 / Math.PI;
|
|
130
|
+
return Object.freeze({
|
|
131
|
+
frame,
|
|
132
|
+
mmPerMeter,
|
|
133
|
+
mmPerPlaneMeter,
|
|
134
|
+
toPaper,
|
|
135
|
+
fromPaper,
|
|
136
|
+
northDegrees: northDegrees + 0
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* This function gives the box on the Earth around the frame, for a fetch of the data of a map. It is the box of 64
|
|
141
|
+
* points on each side of the frame, so it contains the corners and the edges of the frame.
|
|
142
|
+
*
|
|
143
|
+
* @throws MapError - The code is `frame`.
|
|
144
|
+
*/
|
|
145
|
+
function frameBBox(frame) {
|
|
146
|
+
const view = frameView(frame);
|
|
147
|
+
const { widthMm: w, heightMm: h } = frame;
|
|
148
|
+
const points = [];
|
|
149
|
+
const steps = 64;
|
|
150
|
+
for (let i = 0; i < steps; i += 1) {
|
|
151
|
+
const t = i / steps;
|
|
152
|
+
points.push(view.fromPaper({
|
|
153
|
+
x: t * w,
|
|
154
|
+
y: 0
|
|
155
|
+
}), view.fromPaper({
|
|
156
|
+
x: w,
|
|
157
|
+
y: t * h
|
|
158
|
+
}), view.fromPaper({
|
|
159
|
+
x: w - t * w,
|
|
160
|
+
y: h
|
|
161
|
+
}), view.fromPaper({
|
|
162
|
+
x: 0,
|
|
163
|
+
y: h - t * h
|
|
164
|
+
}));
|
|
165
|
+
}
|
|
166
|
+
return bboxOfPoints(points);
|
|
167
|
+
}
|
|
168
|
+
// src/style.ts
|
|
169
|
+
/**
|
|
170
|
+
* The black and white styles of the layers: lines with dashes, areas with gray levels and hatches, and point symbols.
|
|
171
|
+
* The print of a map has no color, so each style uses black, white and gray only.
|
|
172
|
+
*
|
|
173
|
+
* @packageDocumentation
|
|
174
|
+
*/
|
|
175
|
+
const SYMBOLS = [
|
|
176
|
+
"circle",
|
|
177
|
+
"square",
|
|
178
|
+
"triangle",
|
|
179
|
+
"diamond",
|
|
180
|
+
"cross"
|
|
181
|
+
];
|
|
182
|
+
function positive(value, name, layer) {
|
|
183
|
+
if (!(typeof value === "number" && Number.isFinite(value) && value > 0)) throw new MapError("style", `The layer "${layer}": the ${name} ${String(value)} is not a finite number more than 0`);
|
|
184
|
+
}
|
|
185
|
+
function grayLevel(value, layer) {
|
|
186
|
+
if (value === void 0) return;
|
|
187
|
+
if (!(typeof value === "number" && value >= 0 && value <= 1)) throw new MapError("style", `The layer "${layer}": the gray level ${String(value)} is not from 0 to 1`);
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* This function refuses a style that draws nothing, and a size, a gray level, a dash or a symbol that is not correct.
|
|
191
|
+
*
|
|
192
|
+
* @throws MapError - The code is `style`.
|
|
193
|
+
*/
|
|
194
|
+
function checkStyle(style, layer) {
|
|
195
|
+
if (style.stroke === void 0 && style.fill === void 0 && style.point === void 0) throw new MapError("style", `The layer "${layer}": the style has no stroke, no fill and no point, so it draws nothing`);
|
|
196
|
+
if (style.stroke !== void 0) {
|
|
197
|
+
positive(style.stroke.widthMm, "width of the line", layer);
|
|
198
|
+
grayLevel(style.stroke.gray, layer);
|
|
199
|
+
for (const dash of style.stroke.dashMm ?? []) positive(dash, "length of a dash", layer);
|
|
200
|
+
}
|
|
201
|
+
if (style.fill !== void 0) {
|
|
202
|
+
grayLevel(style.fill.gray, layer);
|
|
203
|
+
if (style.fill.gray === void 0 && style.fill.hatch === void 0) throw new MapError("style", `The layer "${layer}": the fill has no gray level and no hatch`);
|
|
204
|
+
const hatch = style.fill.hatch;
|
|
205
|
+
if (hatch !== void 0) {
|
|
206
|
+
positive(hatch.widthMm, "width of a hatch line", layer);
|
|
207
|
+
positive(hatch.spacingMm, "spacing of the hatch", layer);
|
|
208
|
+
if (!Number.isFinite(hatch.angleDegrees)) throw new MapError("style", `The layer "${layer}": the angle ${hatch.angleDegrees} is not finite`);
|
|
209
|
+
if (hatch.spacingMm <= hatch.widthMm) throw new MapError("style", `The layer "${layer}": the spacing of the hatch is not more than its width`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (style.point !== void 0) {
|
|
213
|
+
positive(style.point.sizeMm, "size of the symbol", layer);
|
|
214
|
+
if (!SYMBOLS.includes(style.point.symbol)) throw new MapError("style", `The layer "${layer}": the symbol "${style.point.symbol}" is not one of ${SYMBOLS.join(", ")}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
/** This function gives a number for SVG, to 0.01 mm. */
|
|
218
|
+
function mm(value) {
|
|
219
|
+
return String(Math.round(value * 100) / 100 + 0);
|
|
220
|
+
}
|
|
221
|
+
/** This function gives the color of a gray level, from `#000000` to `#ffffff`. */
|
|
222
|
+
function grayColor(gray) {
|
|
223
|
+
const hex = Math.round(gray * 255).toString(16).padStart(2, "0");
|
|
224
|
+
return `#${hex}${hex}${hex}`;
|
|
225
|
+
}
|
|
226
|
+
/** This function gives the SVG attributes of a line. */
|
|
227
|
+
function strokeAttributes(stroke) {
|
|
228
|
+
const dash = stroke.dashMm === void 0 || stroke.dashMm.length === 0 ? "" : ` stroke-dasharray="${stroke.dashMm.map(mm).join(" ")}"`;
|
|
229
|
+
return `stroke="${grayColor(stroke.gray ?? 0)}" stroke-width="${mm(stroke.widthMm)}"${dash} stroke-linecap="round" stroke-linejoin="round"`;
|
|
230
|
+
}
|
|
231
|
+
/** This function gives the SVG pattern of a hatch, with an identifier. */
|
|
232
|
+
function hatchPattern(id, hatch) {
|
|
233
|
+
const s = mm(hatch.spacingMm);
|
|
234
|
+
const half = mm(hatch.spacingMm / 2);
|
|
235
|
+
const line = `stroke="#000000" stroke-width="${mm(hatch.widthMm)}"`;
|
|
236
|
+
const across = hatch.cross === true ? `<line x1="${half}" y1="0" x2="${half}" y2="${s}" ${line}/>` : "";
|
|
237
|
+
return `<pattern id="${id}" patternUnits="userSpaceOnUse" width="${s}" height="${s}" patternTransform="rotate(${mm(hatch.angleDegrees)})"><line x1="0" y1="${half}" x2="${s}" y2="${half}" ${line}/>${across}</pattern>`;
|
|
238
|
+
}
|
|
239
|
+
/** This function gives the SVG of a point symbol at a point on the paper. */
|
|
240
|
+
function pointSymbol(point, x, y) {
|
|
241
|
+
const r = point.sizeMm / 2;
|
|
242
|
+
const paint = point.filled !== false ? `fill="#000000"` : `fill="#ffffff" stroke="#000000" stroke-width="${mm(point.sizeMm / 8)}"`;
|
|
243
|
+
switch (point.symbol) {
|
|
244
|
+
case "circle": return `<circle cx="${mm(x)}" cy="${mm(y)}" r="${mm(r)}" ${paint}/>`;
|
|
245
|
+
case "square": return `<rect x="${mm(x - r)}" y="${mm(y - r)}" width="${mm(2 * r)}" height="${mm(2 * r)}" ${paint}/>`;
|
|
246
|
+
case "triangle": return `<path d="M${mm(x)} ${mm(y - r)}L${mm(x + r)} ${mm(y + r)}L${mm(x - r)} ${mm(y + r)}Z" ${paint}/>`;
|
|
247
|
+
case "diamond": return `<path d="M${mm(x)} ${mm(y - r)}L${mm(x + r)} ${mm(y)}L${mm(x)} ${mm(y + r)}L${mm(x - r)} ${mm(y)}Z" ${paint}/>`;
|
|
248
|
+
case "cross": return `<path d="M${mm(x - r)} ${mm(y)}L${mm(x + r)} ${mm(y)}M${mm(x)} ${mm(y - r)}L${mm(x)} ${mm(y + r)}" stroke="#000000" stroke-width="${mm(point.sizeMm / 5)}" fill="none"/>`;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
// src/labels.ts
|
|
252
|
+
/**
|
|
253
|
+
* The labels of a map: the names of points, lines and areas, with no overlap.
|
|
254
|
+
*
|
|
255
|
+
* @packageDocumentation
|
|
256
|
+
*/
|
|
257
|
+
/** The gap in millimetres between a point symbol and its label. */
|
|
258
|
+
const POINT_GAP_MM = .6;
|
|
259
|
+
/** The margin in millimetres between a label and the edge of the frame. */
|
|
260
|
+
const FRAME_MARGIN_MM = .5;
|
|
261
|
+
/** The height of the box of a label, as a part of the size of the font. */
|
|
262
|
+
const BOX_HEIGHT = 1.2;
|
|
263
|
+
/** The largest distance from a line to the chord of a label, as a part of the size of the font. */
|
|
264
|
+
const LINE_BEND = .25;
|
|
265
|
+
/**
|
|
266
|
+
* This function examines the label rule of a layer.
|
|
267
|
+
*
|
|
268
|
+
* @throws MapError - The code is `label`.
|
|
269
|
+
*/
|
|
270
|
+
function checkLabelRule(rule, layer) {
|
|
271
|
+
const fail = (reason) => {
|
|
272
|
+
throw new MapError("label", `The labels of the layer "${layer}": ${reason}`);
|
|
273
|
+
};
|
|
274
|
+
if (!Array.isArray(rule.properties) || rule.properties.length === 0) fail("give at least one property");
|
|
275
|
+
for (const property of rule.properties) if (typeof property !== "string" || property === "") fail("each property is a text that is not empty");
|
|
276
|
+
if (!(Number.isFinite(rule.sizeMm) && rule.sizeMm > 0)) fail(`the size ${rule.sizeMm} is not a finite number more than 0`);
|
|
277
|
+
if (rule.priority !== void 0 && !Number.isFinite(rule.priority)) fail(`the priority ${rule.priority} is not a finite number`);
|
|
278
|
+
if (rule.repeatMm !== void 0 && !(Number.isFinite(rule.repeatMm) && rule.repeatMm > 0)) fail(`the distance ${rule.repeatMm} is not a finite number more than 0`);
|
|
279
|
+
}
|
|
280
|
+
/** This function gives the text of the label of a feature: the first property of the rule with a text. */
|
|
281
|
+
function labelText(rule, feature) {
|
|
282
|
+
for (const property of rule.properties) {
|
|
283
|
+
const value = feature.properties?.[property];
|
|
284
|
+
if ((typeof value === "string" || typeof value === "number") && String(value).trim() !== "") return String(value).trim();
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
function corners(box) {
|
|
288
|
+
const c = Math.cos(box.angle);
|
|
289
|
+
const s = Math.sin(box.angle);
|
|
290
|
+
return [
|
|
291
|
+
[-box.hw, -box.hh],
|
|
292
|
+
[box.hw, -box.hh],
|
|
293
|
+
[box.hw, box.hh],
|
|
294
|
+
[-box.hw, box.hh]
|
|
295
|
+
].map(([u, v]) => ({
|
|
296
|
+
x: box.x + u * c - v * s,
|
|
297
|
+
y: box.y + u * s + v * c
|
|
298
|
+
}));
|
|
299
|
+
}
|
|
300
|
+
/** This function tells if two boxes overlap: the test of the separating axis for two rectangles. */
|
|
301
|
+
function overlaps(a, b) {
|
|
302
|
+
const ca = corners(a);
|
|
303
|
+
const cb = corners(b);
|
|
304
|
+
for (const angle of [
|
|
305
|
+
a.angle,
|
|
306
|
+
a.angle + Math.PI / 2,
|
|
307
|
+
b.angle,
|
|
308
|
+
b.angle + Math.PI / 2
|
|
309
|
+
]) {
|
|
310
|
+
const ax = Math.cos(angle);
|
|
311
|
+
const ay = Math.sin(angle);
|
|
312
|
+
const pa = ca.map((p) => p.x * ax + p.y * ay);
|
|
313
|
+
const pb = cb.map((p) => p.x * ax + p.y * ay);
|
|
314
|
+
if (Math.max(...pa) <= Math.min(...pb) || Math.max(...pb) <= Math.min(...pa)) return false;
|
|
315
|
+
}
|
|
316
|
+
return true;
|
|
317
|
+
}
|
|
318
|
+
/** The boxes that a label must not overlap, and the frame. */
|
|
319
|
+
var Room = class {
|
|
320
|
+
boxes = [];
|
|
321
|
+
widthMm;
|
|
322
|
+
heightMm;
|
|
323
|
+
constructor(widthMm, heightMm) {
|
|
324
|
+
this.widthMm = widthMm;
|
|
325
|
+
this.heightMm = heightMm;
|
|
326
|
+
}
|
|
327
|
+
fits(box) {
|
|
328
|
+
for (const p of corners(box)) if (p.x < FRAME_MARGIN_MM || p.y < FRAME_MARGIN_MM || p.x > this.widthMm - FRAME_MARGIN_MM || p.y > this.heightMm - FRAME_MARGIN_MM) return false;
|
|
329
|
+
return !this.boxes.some((other) => overlaps(box, other));
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
function paperOf$1(position, view) {
|
|
333
|
+
return view.toPaper({
|
|
334
|
+
lat: position[1],
|
|
335
|
+
lon: position[0]
|
|
336
|
+
});
|
|
337
|
+
}
|
|
338
|
+
/** This function gives the points, the lines and the areas of a geometry. */
|
|
339
|
+
function parts(geometry, out) {
|
|
340
|
+
switch (geometry.type) {
|
|
341
|
+
case "Point":
|
|
342
|
+
out.points.push(geometry.coordinates);
|
|
343
|
+
break;
|
|
344
|
+
case "MultiPoint":
|
|
345
|
+
out.points.push(...geometry.coordinates);
|
|
346
|
+
break;
|
|
347
|
+
case "LineString":
|
|
348
|
+
out.lines.push(geometry.coordinates);
|
|
349
|
+
break;
|
|
350
|
+
case "MultiLineString":
|
|
351
|
+
out.lines.push(...geometry.coordinates);
|
|
352
|
+
break;
|
|
353
|
+
case "Polygon":
|
|
354
|
+
out.areas.push(geometry);
|
|
355
|
+
break;
|
|
356
|
+
case "MultiPolygon":
|
|
357
|
+
for (const coordinates of geometry.coordinates) out.areas.push({
|
|
358
|
+
type: "Polygon",
|
|
359
|
+
coordinates
|
|
360
|
+
});
|
|
361
|
+
break;
|
|
362
|
+
case "GeometryCollection": for (const item of geometry.geometries) parts(item, out);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
/** This function gives the angle of a direction in radians, more than -pi/2 and not more than pi/2, so the text reads from the left. */
|
|
366
|
+
function readable(dx, dy) {
|
|
367
|
+
let angle = Math.atan2(dy, dx);
|
|
368
|
+
if (angle > Math.PI / 2) angle -= Math.PI;
|
|
369
|
+
if (angle <= -Math.PI / 2) angle += Math.PI;
|
|
370
|
+
return angle;
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* This function gives the runs of a line on the paper: the parts with each segment in a box that touches the frame. So
|
|
374
|
+
* a segment that crosses the frame stays in its run. A run can go past the frame, but a label box outside the frame
|
|
375
|
+
* does not fit.
|
|
376
|
+
*/
|
|
377
|
+
function runs(line, view) {
|
|
378
|
+
const { widthMm: w, heightMm: h } = view.frame;
|
|
379
|
+
const points = line.map((position) => paperOf$1(position, view));
|
|
380
|
+
const out = [];
|
|
381
|
+
let run = [];
|
|
382
|
+
for (let i = 1; i < points.length; i += 1) {
|
|
383
|
+
const a = points[i - 1];
|
|
384
|
+
const b = points[i];
|
|
385
|
+
if (Math.max(a.x, b.x) >= 0 && Math.min(a.x, b.x) <= w && Math.max(a.y, b.y) >= 0 && Math.min(a.y, b.y) <= h) {
|
|
386
|
+
if (run.length === 0) run.push(a);
|
|
387
|
+
run.push(b);
|
|
388
|
+
} else {
|
|
389
|
+
if (run.length > 1) out.push(run);
|
|
390
|
+
run = [];
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (run.length > 1) out.push(run);
|
|
394
|
+
return out;
|
|
395
|
+
}
|
|
396
|
+
/** This function gives the length of a run on the paper. */
|
|
397
|
+
function runLength(run) {
|
|
398
|
+
let total = 0;
|
|
399
|
+
for (let i = 1; i < run.length; i += 1) total += Math.hypot(run[i].x - run[i - 1].x, run[i].y - run[i - 1].y);
|
|
400
|
+
return total;
|
|
401
|
+
}
|
|
402
|
+
/** This function gives the point at a distance along a run, with the cumulative lengths of the run. */
|
|
403
|
+
function along(run, lengths, s) {
|
|
404
|
+
let i = 1;
|
|
405
|
+
while (i < run.length - 1 && lengths[i] < s) i += 1;
|
|
406
|
+
const a = run[i - 1];
|
|
407
|
+
const b = run[i];
|
|
408
|
+
const span = lengths[i] - lengths[i - 1];
|
|
409
|
+
const t = span === 0 ? 0 : (s - lengths[i - 1]) / span;
|
|
410
|
+
return {
|
|
411
|
+
x: a.x + t * (b.x - a.x),
|
|
412
|
+
y: a.y + t * (b.y - a.y)
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/**
|
|
416
|
+
* This function gives the boxes of a label along a run, from the middle of the run to its ends. A box is on an almost
|
|
417
|
+
* straight part of the run. No point of that part is farther from the chord than `LINE_BEND` of the size.
|
|
418
|
+
*/
|
|
419
|
+
function lineCandidates(run, width, size) {
|
|
420
|
+
const lengths = [0];
|
|
421
|
+
for (let i = 1; i < run.length; i += 1) lengths.push(lengths[i - 1] + Math.hypot(run[i].x - run[i - 1].x, run[i].y - run[i - 1].y));
|
|
422
|
+
const total = lengths.at(-1);
|
|
423
|
+
const span = width + 2;
|
|
424
|
+
if (total < span) return [];
|
|
425
|
+
const step = Math.max(span / 4, 2);
|
|
426
|
+
const middles = [total / 2];
|
|
427
|
+
for (let k = 1; k * step <= total / 2 - span / 2; k += 1) middles.push(total / 2 - k * step, total / 2 + k * step);
|
|
428
|
+
const boxes = [];
|
|
429
|
+
for (const middle of middles) {
|
|
430
|
+
const start = along(run, lengths, middle - span / 2);
|
|
431
|
+
const end = along(run, lengths, middle + span / 2);
|
|
432
|
+
const chord = Math.hypot(end.x - start.x, end.y - start.y);
|
|
433
|
+
if (chord < .9 * span) continue;
|
|
434
|
+
const inside = run.filter((_, i) => lengths[i] > middle - span / 2 && lengths[i] < middle + span / 2);
|
|
435
|
+
if (Math.max(0, ...inside.map((p) => Math.abs((end.x - start.x) * (start.y - p.y) - (start.x - p.x) * (end.y - start.y)) / chord)) > LINE_BEND * size) continue;
|
|
436
|
+
boxes.push({
|
|
437
|
+
x: (start.x + end.x) / 2,
|
|
438
|
+
y: (start.y + end.y) / 2,
|
|
439
|
+
hw: width / 2,
|
|
440
|
+
hh: BOX_HEIGHT * size / 2,
|
|
441
|
+
angle: readable(end.x - start.x, end.y - start.y)
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
return boxes;
|
|
445
|
+
}
|
|
446
|
+
/** This function gives the boxes of a label around a point, in the sequence of the preferred places. */
|
|
447
|
+
function pointCandidates(p, width, size, symbolMm) {
|
|
448
|
+
const hw = width / 2;
|
|
449
|
+
const hh = BOX_HEIGHT * size / 2;
|
|
450
|
+
const d = symbolMm / 2 + POINT_GAP_MM;
|
|
451
|
+
const k = d * Math.SQRT1_2;
|
|
452
|
+
return [
|
|
453
|
+
[d + hw, 0],
|
|
454
|
+
[-d - hw, 0],
|
|
455
|
+
[0, -d - hh],
|
|
456
|
+
[0, d + hh],
|
|
457
|
+
[k + hw, -k - hh],
|
|
458
|
+
[k + hw, k + hh],
|
|
459
|
+
[-k - hw, -k - hh],
|
|
460
|
+
[-k - hw, k + hh]
|
|
461
|
+
].map(([dx, dy]) => ({
|
|
462
|
+
x: p.x + dx,
|
|
463
|
+
y: p.y + dy,
|
|
464
|
+
hw,
|
|
465
|
+
hh,
|
|
466
|
+
angle: 0
|
|
467
|
+
}));
|
|
468
|
+
}
|
|
469
|
+
/** This function gives the box of a label in the middle of an area, when the area has each corner of the box. */
|
|
470
|
+
function areaCandidates(area, view, width, size) {
|
|
471
|
+
const ring = area.coordinates[0] ?? [];
|
|
472
|
+
if (ring.length < 4) return [];
|
|
473
|
+
const points = ring.map((position) => paperOf$1(position, view));
|
|
474
|
+
let doubled = 0;
|
|
475
|
+
let cx = 0;
|
|
476
|
+
let cy = 0;
|
|
477
|
+
for (let i = 0; i + 1 < points.length; i += 1) {
|
|
478
|
+
const a = points[i];
|
|
479
|
+
const b = points[i + 1];
|
|
480
|
+
const cross = a.x * b.y - b.x * a.y;
|
|
481
|
+
doubled += cross;
|
|
482
|
+
cx += (a.x + b.x) * cross;
|
|
483
|
+
cy += (a.y + b.y) * cross;
|
|
484
|
+
}
|
|
485
|
+
const xs = points.map((p) => p.x);
|
|
486
|
+
const ys = points.map((p) => p.y);
|
|
487
|
+
const middle = {
|
|
488
|
+
x: (Math.min(...xs) + Math.max(...xs)) / 2,
|
|
489
|
+
y: (Math.min(...ys) + Math.max(...ys)) / 2
|
|
490
|
+
};
|
|
491
|
+
const centers = doubled === 0 ? [middle] : [{
|
|
492
|
+
x: cx / (3 * doubled),
|
|
493
|
+
y: cy / (3 * doubled)
|
|
494
|
+
}, middle];
|
|
495
|
+
const hw = width / 2;
|
|
496
|
+
const hh = BOX_HEIGHT * size / 2;
|
|
497
|
+
return centers.map((c) => ({
|
|
498
|
+
x: c.x,
|
|
499
|
+
y: c.y,
|
|
500
|
+
hw,
|
|
501
|
+
hh,
|
|
502
|
+
angle: 0
|
|
503
|
+
})).filter((box) => [...corners(box), {
|
|
504
|
+
x: box.x,
|
|
505
|
+
y: box.y
|
|
506
|
+
}].every((p) => locatePoint(view.fromPaper(p), area) === "inside"));
|
|
507
|
+
}
|
|
508
|
+
/** This function tells if the box of the outer ring of an area on the paper touches the frame. */
|
|
509
|
+
function areaOnFrame(area, view) {
|
|
510
|
+
const points = (area.coordinates[0] ?? []).map((position) => paperOf$1(position, view));
|
|
511
|
+
const xs = points.map((p) => p.x);
|
|
512
|
+
const ys = points.map((p) => p.y);
|
|
513
|
+
return points.length > 0 && Math.max(...xs) >= 0 && Math.min(...xs) <= view.frame.widthMm && Math.max(...ys) >= 0 && Math.min(...ys) <= view.frame.heightMm;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* This function gives the places of the labels of the layers. The labels do not overlap, and each label is inside the
|
|
517
|
+
* frame.
|
|
518
|
+
*
|
|
519
|
+
* - The layers with a lower `priority` get their places first. With the same priority, a higher layer is first.
|
|
520
|
+
* - In a layer, the features with the same text are one job. A longer line is first, then the sequence of the features.
|
|
521
|
+
* - A point gets the first free place of 8 places around its symbol: right, left, above, below, then the corners.
|
|
522
|
+
* - A line gets its text along an almost straight part. The longest run is first, and the middle of a run is first.
|
|
523
|
+
* - With `repeatMm`, a line gets more labels of its text, at that distance or more from each other.
|
|
524
|
+
* - An area gets its text at its centroid or at the middle of its box, when the area has the box of the text.
|
|
525
|
+
* - Each point symbol of the layers and the north arrow are obstacles too.
|
|
526
|
+
* - A text with a part on the frame and no free place is in `skipped`. A text with no part on the frame is in neither list.
|
|
527
|
+
*
|
|
528
|
+
* @param obstacles - The boxes on the paper that no label covers, as the middle and the half size in millimetres.
|
|
529
|
+
* @throws MapError - The code is `label`: the width of a text from `measure` is not a finite number of 0 or more.
|
|
530
|
+
*/
|
|
531
|
+
function placeLabels(layers, view, font, obstacles = []) {
|
|
532
|
+
const room = new Room(view.frame.widthMm, view.frame.heightMm);
|
|
533
|
+
for (const o of obstacles) room.boxes.push({
|
|
534
|
+
x: o.x,
|
|
535
|
+
y: o.y,
|
|
536
|
+
hw: o.half,
|
|
537
|
+
hh: o.half,
|
|
538
|
+
angle: 0
|
|
539
|
+
});
|
|
540
|
+
for (const layer of layers) {
|
|
541
|
+
if (layer.pointSizeMm === void 0) continue;
|
|
542
|
+
const out = {
|
|
543
|
+
points: [],
|
|
544
|
+
lines: [],
|
|
545
|
+
areas: []
|
|
546
|
+
};
|
|
547
|
+
for (const feature of layer.features) if (feature.geometry !== null) parts(feature.geometry, out);
|
|
548
|
+
for (const position of out.points) {
|
|
549
|
+
const p = paperOf$1(position, view);
|
|
550
|
+
room.boxes.push({
|
|
551
|
+
x: p.x,
|
|
552
|
+
y: p.y,
|
|
553
|
+
hw: layer.pointSizeMm / 2,
|
|
554
|
+
hh: layer.pointSizeMm / 2,
|
|
555
|
+
angle: 0
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
const order = layers.map((layer, index) => ({
|
|
560
|
+
layer,
|
|
561
|
+
index
|
|
562
|
+
})).filter((entry) => entry.layer.label !== void 0).sort((a, b) => (a.layer.label.priority ?? 0) - (b.layer.label.priority ?? 0) || b.index - a.index);
|
|
563
|
+
const placed = [];
|
|
564
|
+
const skipped = [];
|
|
565
|
+
for (const { layer } of order) {
|
|
566
|
+
const rule = layer.label;
|
|
567
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
568
|
+
for (const feature of layer.features) {
|
|
569
|
+
if (feature.geometry === null) continue;
|
|
570
|
+
const text = labelText(rule, feature);
|
|
571
|
+
if (text === void 0) continue;
|
|
572
|
+
let job = jobs.get(text);
|
|
573
|
+
if (job === void 0) {
|
|
574
|
+
const width = font.measure(text, rule.sizeMm);
|
|
575
|
+
if (!(Number.isFinite(width) && width >= 0)) throw new MapError("label", `The width ${width} of the label "${text}" is not a finite number of 0 or more`);
|
|
576
|
+
job = {
|
|
577
|
+
layer,
|
|
578
|
+
rule,
|
|
579
|
+
text,
|
|
580
|
+
width,
|
|
581
|
+
points: [],
|
|
582
|
+
lines: [],
|
|
583
|
+
areas: []
|
|
584
|
+
};
|
|
585
|
+
jobs.set(text, job);
|
|
586
|
+
}
|
|
587
|
+
parts(feature.geometry, job);
|
|
588
|
+
}
|
|
589
|
+
const sorted = [...jobs.values()].map((job) => {
|
|
590
|
+
const lineRuns = job.lines.flatMap((line) => runs(line, view)).map((run) => ({
|
|
591
|
+
run,
|
|
592
|
+
length: runLength(run)
|
|
593
|
+
})).sort((a, b) => b.length - a.length);
|
|
594
|
+
return {
|
|
595
|
+
job,
|
|
596
|
+
lineRuns,
|
|
597
|
+
length: lineRuns.reduce((t, entry) => t + entry.length, 0)
|
|
598
|
+
};
|
|
599
|
+
}).sort((a, b) => b.length - a.length);
|
|
600
|
+
for (const { job, lineRuns } of sorted) {
|
|
601
|
+
const mine = [];
|
|
602
|
+
let onFrame = false;
|
|
603
|
+
const take = (box) => {
|
|
604
|
+
if (!room.fits(box)) return false;
|
|
605
|
+
if (job.rule.repeatMm !== void 0 && mine.some((other) => Math.hypot(other.x - box.x, other.y - box.y) < job.rule.repeatMm)) return false;
|
|
606
|
+
room.boxes.push(box);
|
|
607
|
+
mine.push({
|
|
608
|
+
layer: layer.id,
|
|
609
|
+
text: job.text,
|
|
610
|
+
x: box.x,
|
|
611
|
+
y: box.y,
|
|
612
|
+
angle: box.angle * 180 / Math.PI + 0,
|
|
613
|
+
sizeMm: job.rule.sizeMm,
|
|
614
|
+
widthMm: job.width
|
|
615
|
+
});
|
|
616
|
+
return true;
|
|
617
|
+
};
|
|
618
|
+
for (const position of job.points) {
|
|
619
|
+
const p = paperOf$1(position, view);
|
|
620
|
+
if (p.x < 0 || p.y < 0 || p.x > view.frame.widthMm || p.y > view.frame.heightMm) continue;
|
|
621
|
+
onFrame = true;
|
|
622
|
+
pointCandidates(p, job.width, job.rule.sizeMm, layer.pointSizeMm ?? 0).some(take);
|
|
623
|
+
}
|
|
624
|
+
if (lineRuns.length > 0) onFrame = true;
|
|
625
|
+
lines: for (const { run } of lineRuns) for (const box of lineCandidates(run, job.width, job.rule.sizeMm)) if (take(box) && job.rule.repeatMm === void 0) break lines;
|
|
626
|
+
for (const area of job.areas) {
|
|
627
|
+
if (!areaOnFrame(area, view)) continue;
|
|
628
|
+
onFrame = true;
|
|
629
|
+
areaCandidates(area, view, job.width, job.rule.sizeMm).some(take);
|
|
630
|
+
}
|
|
631
|
+
if (mine.length === 0 && onFrame) skipped.push({
|
|
632
|
+
layer: layer.id,
|
|
633
|
+
text: job.text
|
|
634
|
+
});
|
|
635
|
+
placed.push(...mine);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
placed,
|
|
640
|
+
skipped
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
/** This function gives the SVG of the labels: black text with a white halo, so a label reads over the lines of the map. */
|
|
644
|
+
function labelsSvg(placement, font) {
|
|
645
|
+
const texts = placement.placed.map((label) => {
|
|
646
|
+
const rotate = label.angle === 0 ? "" : ` transform="rotate(${mm(label.angle)} ${mm(label.x)} ${mm(label.y)})"`;
|
|
647
|
+
return `<text x="${mm(label.x)}" y="${mm(label.y)}" font-size="${mm(label.sizeMm)}"${rotate} text-anchor="middle" dominant-baseline="central" fill="#000000" stroke="#ffffff" stroke-width="${mm(label.sizeMm * .25)}" stroke-linejoin="round" paint-order="stroke">${escapeHtml(label.text)}</text>`;
|
|
648
|
+
});
|
|
649
|
+
return `<g class="labels" font-family="${escapeAttribute(font.family)}" data-skipped="${placement.skipped.length}">${texts.join("")}</g>`;
|
|
650
|
+
}
|
|
651
|
+
// src/marks.ts
|
|
652
|
+
/**
|
|
653
|
+
* The marks of a map: the scale bar and the north arrow.
|
|
654
|
+
*
|
|
655
|
+
* @packageDocumentation
|
|
656
|
+
*/
|
|
657
|
+
const METERS_PER_MILE = 1609.344;
|
|
658
|
+
const METERS_PER_FOOT = .3048;
|
|
659
|
+
/** This function gives the largest number 1, 2 or 5 times a power of 10 that is not more than a number more than 0. */
|
|
660
|
+
function niceNumber(max) {
|
|
661
|
+
const power = 10 ** Math.floor(Math.log10(max));
|
|
662
|
+
for (const step of [
|
|
663
|
+
5,
|
|
664
|
+
2,
|
|
665
|
+
1
|
|
666
|
+
]) {
|
|
667
|
+
const value = Number((step * power).toPrecision(1));
|
|
668
|
+
if (value <= max) return value;
|
|
669
|
+
}
|
|
670
|
+
return Number((power / 2).toPrecision(1));
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* This function gives the length of a scale bar that is not longer than a length on the ground.
|
|
674
|
+
*
|
|
675
|
+
* - The metric bar is in metres below 1 km, and in kilometres from 1 km.
|
|
676
|
+
* - The imperial bar is in miles from a quarter of a mile, and in feet below that.
|
|
677
|
+
*/
|
|
678
|
+
function scaleBarLength(maxMeters, units) {
|
|
679
|
+
if (units === "metric") {
|
|
680
|
+
const meters = niceNumber(maxMeters);
|
|
681
|
+
return {
|
|
682
|
+
meters,
|
|
683
|
+
label: meters >= 1e3 ? `${meters / 1e3} km` : `${meters} m`
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
const miles = maxMeters / METERS_PER_MILE;
|
|
687
|
+
if (miles >= .25) {
|
|
688
|
+
const value = niceNumber(miles);
|
|
689
|
+
return {
|
|
690
|
+
meters: value * METERS_PER_MILE,
|
|
691
|
+
label: `${value} mi`
|
|
692
|
+
};
|
|
693
|
+
}
|
|
694
|
+
const feet = niceNumber(maxMeters / METERS_PER_FOOT);
|
|
695
|
+
return {
|
|
696
|
+
meters: feet * METERS_PER_FOOT,
|
|
697
|
+
label: `${feet} ft`
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
/** The height of one scale bar with its label, in millimetres. */
|
|
701
|
+
const SCALE_BAR_ROW_MM = 4.5;
|
|
702
|
+
/** This function gives the SVG of a scale bar of four parts, with its top left corner at a point on the paper. */
|
|
703
|
+
function scaleBarSvg(x, y, length, mmPerMeter) {
|
|
704
|
+
const total = length.meters * mmPerMeter;
|
|
705
|
+
const part = total / 4;
|
|
706
|
+
let parts = "";
|
|
707
|
+
for (let i = 0; i < 4; i += 1) parts += `<rect x="${mm(x + i * part)}" y="${mm(y)}" width="${mm(part)}" height="1.5" fill="${i % 2 === 0 ? "#000000" : "#ffffff"}" stroke="#000000" stroke-width="0.15"/>`;
|
|
708
|
+
return `<g class="scale-bar">${parts}<text x="${mm(x + total + 1.5)}" y="${mm(y + 1.5)}" font-size="2.4">${escapeHtml(length.label)}</text></g>`;
|
|
709
|
+
}
|
|
710
|
+
/** This function gives the SVG of a north arrow at a point on the paper, with the direction of north in degrees. */
|
|
711
|
+
function northArrowSvg(x, y, northDegrees) {
|
|
712
|
+
return `<g class="north-arrow" transform="translate(${mm(x)} ${mm(y)}) rotate(${mm(northDegrees)})"><circle r="4.5" fill="#ffffff" stroke="#000000" stroke-width="0.2"/><path d="M0 -3.6L1.6 1.2L0 0.4L-1.6 1.2Z" fill="#000000"/><text y="3.9" font-size="2.2" text-anchor="middle">N</text></g>`;
|
|
713
|
+
}
|
|
714
|
+
// src/render.ts
|
|
715
|
+
/**
|
|
716
|
+
* A map as data, and its render to SVG.
|
|
717
|
+
*
|
|
718
|
+
* @packageDocumentation
|
|
719
|
+
*/
|
|
720
|
+
const LEGEND_PLACES = ["below", "side"];
|
|
721
|
+
const ID = /^[a-z][a-z0-9-]*$/;
|
|
722
|
+
function checkId(id, what) {
|
|
723
|
+
if (!ID.test(id)) throw new MapError("id", `The identifier "${id}" of the ${what} is not lower case letters, digits and hyphens that start with a letter`);
|
|
724
|
+
}
|
|
725
|
+
function checkSource(source, layer) {
|
|
726
|
+
if (source === void 0 || typeof source !== "object") throw new MapError("source", `The layer "${layer}" has no source`);
|
|
727
|
+
if (typeof source.title !== "string" || source.title.trim() === "") throw new MapError("source", `The source of the layer "${layer}" has no title`);
|
|
728
|
+
if (typeof source.license !== "string" || source.license.trim() === "") throw new MapError("source", `The source of the layer "${layer}" has no license`);
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* This function examines a map. It refuses a frame, an identifier, a style, a filter or a source that is not correct.
|
|
732
|
+
* Each layer must have a source with a title and a license, so the attribution block names each source of the map.
|
|
733
|
+
*
|
|
734
|
+
* @throws MapError - The code tells the reason.
|
|
735
|
+
*/
|
|
736
|
+
function checkMap(map) {
|
|
737
|
+
checkId(map.id, "map");
|
|
738
|
+
frameView(map.frame);
|
|
739
|
+
if (map.legendPlace !== void 0 && !LEGEND_PLACES.includes(map.legendPlace)) throw new MapError("style", `The place of the legend "${String(map.legendPlace)}" is not "below" or "side"`);
|
|
740
|
+
const ids = /* @__PURE__ */ new Set();
|
|
741
|
+
for (const layer of map.layers) {
|
|
742
|
+
checkId(layer.id, "layer");
|
|
743
|
+
if (ids.has(layer.id)) throw new MapError("id", `Two layers have the identifier "${layer.id}"`);
|
|
744
|
+
ids.add(layer.id);
|
|
745
|
+
checkSource(layer.source, layer.id);
|
|
746
|
+
checkStyle(layer.style, layer.id);
|
|
747
|
+
if (layer.filter !== void 0) checkFilter(layer.filter, `layer "${layer.id}" filter`);
|
|
748
|
+
if (layer.label !== void 0) checkLabelRule(layer.label, layer.id);
|
|
749
|
+
if (layer.simplifyMm !== void 0 && !(Number.isFinite(layer.simplifyMm) && layer.simplifyMm > 0)) throw new MapError("style", `The layer "${layer.id}": the tolerance ${layer.simplifyMm} is not a finite number more than 0`);
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
/** The box of the points on the paper that a feature uses. */
|
|
753
|
+
var PaperBox = class {
|
|
754
|
+
minX = Number.POSITIVE_INFINITY;
|
|
755
|
+
minY = Number.POSITIVE_INFINITY;
|
|
756
|
+
maxX = Number.NEGATIVE_INFINITY;
|
|
757
|
+
maxY = Number.NEGATIVE_INFINITY;
|
|
758
|
+
add(point) {
|
|
759
|
+
this.minX = Math.min(this.minX, point.x);
|
|
760
|
+
this.minY = Math.min(this.minY, point.y);
|
|
761
|
+
this.maxX = Math.max(this.maxX, point.x);
|
|
762
|
+
this.maxY = Math.max(this.maxY, point.y);
|
|
763
|
+
}
|
|
764
|
+
/** It tells if the box touches the frame, with a margin in millimetres. */
|
|
765
|
+
touches(frame, margin) {
|
|
766
|
+
return this.maxX >= -margin && this.minX <= frame.widthMm + margin && this.maxY >= -margin && this.minY <= frame.heightMm + margin;
|
|
767
|
+
}
|
|
768
|
+
};
|
|
769
|
+
function paperOf(position, view) {
|
|
770
|
+
return view.toPaper({
|
|
771
|
+
lat: position[1],
|
|
772
|
+
lon: position[0]
|
|
773
|
+
});
|
|
774
|
+
}
|
|
775
|
+
function linePath(positions, view, box, close) {
|
|
776
|
+
let d = "";
|
|
777
|
+
positions.forEach((position, i) => {
|
|
778
|
+
const point = paperOf(position, view);
|
|
779
|
+
box.add(point);
|
|
780
|
+
d += `${i === 0 ? "M" : "L"}${mm(point.x)} ${mm(point.y)}`;
|
|
781
|
+
});
|
|
782
|
+
return close ? `${d}Z` : d;
|
|
783
|
+
}
|
|
784
|
+
/** This function gives the SVG of one geometry with a style. */
|
|
785
|
+
function drawGeometry(geometry, style, view, fill) {
|
|
786
|
+
const frame = view.frame;
|
|
787
|
+
switch (geometry.type) {
|
|
788
|
+
case "Point":
|
|
789
|
+
case "MultiPoint":
|
|
790
|
+
if (style.point === void 0) return "";
|
|
791
|
+
return (geometry.type === "Point" ? [geometry.coordinates] : geometry.coordinates).map((position) => paperOf(position, view)).filter((point) => point.x >= -style.point.sizeMm && point.x <= frame.widthMm + style.point.sizeMm && point.y >= -style.point.sizeMm && point.y <= frame.heightMm + style.point.sizeMm).map((point) => pointSymbol(style.point, point.x, point.y)).join("");
|
|
792
|
+
case "LineString":
|
|
793
|
+
case "MultiLineString": {
|
|
794
|
+
if (style.stroke === void 0) return "";
|
|
795
|
+
const box = new PaperBox();
|
|
796
|
+
const d = (geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates).map((line) => linePath(line, view, box, false)).join("");
|
|
797
|
+
if (!box.touches(frame, style.stroke.widthMm)) return "";
|
|
798
|
+
return `<path d="${d}" fill="none" ${strokeAttributes(style.stroke)}/>`;
|
|
799
|
+
}
|
|
800
|
+
case "Polygon":
|
|
801
|
+
case "MultiPolygon": {
|
|
802
|
+
const box = new PaperBox();
|
|
803
|
+
const d = (geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates).flatMap((rings) => rings.map((ring) => linePath(ring, view, box, true))).join("");
|
|
804
|
+
if (!box.touches(frame, style.stroke?.widthMm ?? 0)) return "";
|
|
805
|
+
const stroke = style.stroke === void 0 ? `stroke="none"` : strokeAttributes(style.stroke);
|
|
806
|
+
let svg = "";
|
|
807
|
+
if (style.fill?.gray !== void 0) svg += `<path d="${d}" fill="${grayColor(style.fill.gray)}" fill-rule="evenodd" stroke="none"/>`;
|
|
808
|
+
svg += `<path d="${d}" fill="${fill ?? "none"}" fill-rule="evenodd" ${stroke}/>`;
|
|
809
|
+
return svg;
|
|
810
|
+
}
|
|
811
|
+
case "GeometryCollection": return geometry.geometries.map((item) => drawGeometry(item, style, view, fill)).join("");
|
|
812
|
+
}
|
|
813
|
+
}
|
|
814
|
+
/** This function gives the features of a layer after its filter and its simplification. */
|
|
815
|
+
function featuresOf(layer, frame) {
|
|
816
|
+
const kept = layer.features.filter((feature) => feature.geometry !== null && (layer.filter === void 0 || matchesFilter(layer.filter, feature)));
|
|
817
|
+
if (layer.simplifyMm === void 0) return kept;
|
|
818
|
+
const areas = kept.flatMap((feature, i) => feature.geometry?.type === "Polygon" || feature.geometry?.type === "MultiPolygon" ? [i] : []);
|
|
819
|
+
if (areas.length === 0) return kept;
|
|
820
|
+
const simplified = simplifyRegions(areas.map((i) => kept[i].geometry), layer.simplifyMm * frame.scale / 1e6);
|
|
821
|
+
const result = [...kept];
|
|
822
|
+
areas.forEach((index, j) => {
|
|
823
|
+
result[index] = {
|
|
824
|
+
...kept[index],
|
|
825
|
+
geometry: simplified[j]
|
|
826
|
+
};
|
|
827
|
+
});
|
|
828
|
+
return result;
|
|
829
|
+
}
|
|
830
|
+
/** The middle of the north arrow, from the top right corner of the frame, and the half size of its box, in millimetres. */
|
|
831
|
+
const NORTH_ARROW = {
|
|
832
|
+
inset: 6.5,
|
|
833
|
+
half: 4.7
|
|
834
|
+
};
|
|
835
|
+
function placementOf(map, features, view, font) {
|
|
836
|
+
const obstacles = map.northArrow === false ? [] : [{
|
|
837
|
+
x: map.frame.widthMm - NORTH_ARROW.inset,
|
|
838
|
+
y: NORTH_ARROW.inset,
|
|
839
|
+
half: NORTH_ARROW.half
|
|
840
|
+
}];
|
|
841
|
+
return placeLabels(map.layers.map((layer, i) => ({
|
|
842
|
+
id: layer.id,
|
|
843
|
+
features: features[i],
|
|
844
|
+
label: layer.label,
|
|
845
|
+
pointSizeMm: layer.style.point?.sizeMm
|
|
846
|
+
})), view, font, obstacles);
|
|
847
|
+
}
|
|
848
|
+
function labelFontOf(map, options) {
|
|
849
|
+
const labelled = map.layers.find((layer) => layer.label !== void 0);
|
|
850
|
+
if (labelled === void 0) return void 0;
|
|
851
|
+
const font = options.labelFont;
|
|
852
|
+
if (font === void 0 || typeof font.measure !== "function" || typeof font.family !== "string" || font.family.trim() === "") throw new MapError("label", `The layer "${labelled.id}" has labels, so the options need a label font with a family and a measure`);
|
|
853
|
+
return font;
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* This function gives the labels of a map with their places, and the texts with no place. `renderMap` draws the same
|
|
857
|
+
* labels.
|
|
858
|
+
*
|
|
859
|
+
* @throws MapError - The map is not correct, as `checkMap` tells, or a layer has labels and the options have no font.
|
|
860
|
+
*/
|
|
861
|
+
function mapLabels(map, options = {}) {
|
|
862
|
+
checkMap(map);
|
|
863
|
+
const font = labelFontOf(map, options);
|
|
864
|
+
if (font === void 0) return {
|
|
865
|
+
placed: [],
|
|
866
|
+
skipped: []
|
|
867
|
+
};
|
|
868
|
+
return placementOf(map, map.layers.map((layer) => featuresOf(layer, map.frame)), frameView(map.frame), font);
|
|
869
|
+
}
|
|
870
|
+
/** This function gives the swatch of a layer in the legend, with its top left corner at a point. */
|
|
871
|
+
function swatch(style, x, y, fill) {
|
|
872
|
+
if (style.point !== void 0) return pointSymbol(style.point, x + 3, y + 1.75);
|
|
873
|
+
if (style.fill !== void 0) {
|
|
874
|
+
const stroke = style.stroke === void 0 ? `stroke="#000000" stroke-width="0.1"` : strokeAttributes(style.stroke);
|
|
875
|
+
return `${style.fill.gray === void 0 ? "" : `<rect x="${mm(x)}" y="${mm(y)}" width="6" height="3.5" fill="${grayColor(style.fill.gray)}"/>`}<rect x="${mm(x)}" y="${mm(y)}" width="6" height="3.5" fill="${fill ?? "none"}" ${stroke}/>`;
|
|
876
|
+
}
|
|
877
|
+
return `<path d="M${mm(x)} ${mm(y + 1.75)}L${mm(x + 6)} ${mm(y + 1.75)}" ${strokeAttributes(style.stroke)}/>`;
|
|
878
|
+
}
|
|
879
|
+
function thousands(value) {
|
|
880
|
+
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
881
|
+
}
|
|
882
|
+
/** The space between the frame and the column of the legend at the side, in millimetres. */
|
|
883
|
+
const SIDE_GAP_MM = 3;
|
|
884
|
+
/** The space above the first row of the column of the legend at the side, in millimetres. */
|
|
885
|
+
const SIDE_TOP_MM = 1;
|
|
886
|
+
/** The least width of the column of the legend at the side, in millimetres. */
|
|
887
|
+
const SIDE_LEAST_WIDTH_MM = 30;
|
|
888
|
+
/** The space between the scale bars and the legend in the column at the side, in millimetres. */
|
|
889
|
+
const SIDE_GROUP_GAP_MM = 1.5;
|
|
890
|
+
/** The space at the right of a scale bar in the column at the side for its label, in millimetres. */
|
|
891
|
+
const SCALE_LABEL_MM = 12;
|
|
892
|
+
/** The size of the font of the legend texts, in millimetres. */
|
|
893
|
+
const LEGEND_TEXT_MM = 2.4;
|
|
894
|
+
/** The distance from the left side of a swatch to its text, in millimetres. */
|
|
895
|
+
const LEGEND_TEXT_X_MM = 7.5;
|
|
896
|
+
/** The width of a character of a legend text, as a part of the size of the font, when the options have no font. */
|
|
897
|
+
const CHARACTER_WIDTH = .6;
|
|
898
|
+
/** This function gives the font that measures the legend texts: the label font of the options, if it has a measure. */
|
|
899
|
+
function measureFontOf(options) {
|
|
900
|
+
const font = options.labelFont;
|
|
901
|
+
return font !== void 0 && typeof font.measure === "function" ? font : void 0;
|
|
902
|
+
}
|
|
903
|
+
function legendLayout(map, font) {
|
|
904
|
+
const units = map.scaleBar ?? "both";
|
|
905
|
+
const bars = units === "none" ? [] : units === "both" ? ["metric", "imperial"] : [units];
|
|
906
|
+
const texts = map.layers.flatMap((layer) => layer.legend === void 0 ? [] : [layer.legend]);
|
|
907
|
+
const lines = attributionLines(map);
|
|
908
|
+
const place = map.legendPlace ?? "below";
|
|
909
|
+
if (place === "below" || bars.length + texts.length === 0) return {
|
|
910
|
+
bars,
|
|
911
|
+
lines,
|
|
912
|
+
columnMm: 0,
|
|
913
|
+
columnHeightMm: 0,
|
|
914
|
+
blockMm: place === "below" ? Math.max(bars.length, Math.ceil(texts.length / 2)) * SCALE_BAR_ROW_MM : 0
|
|
915
|
+
};
|
|
916
|
+
const width = (text) => font === void 0 ? text.length * LEGEND_TEXT_MM * CHARACTER_WIDTH : font.measure(text, LEGEND_TEXT_MM);
|
|
917
|
+
const widest = Math.max(0, ...texts.map(width));
|
|
918
|
+
const columnMm = Math.max(SIDE_LEAST_WIDTH_MM, LEGEND_TEXT_X_MM + widest + 1);
|
|
919
|
+
const gap = bars.length > 0 && texts.length > 0 ? SIDE_GROUP_GAP_MM : 0;
|
|
920
|
+
return {
|
|
921
|
+
bars,
|
|
922
|
+
lines,
|
|
923
|
+
columnMm,
|
|
924
|
+
columnHeightMm: SIDE_TOP_MM + (bars.length + texts.length) * SCALE_BAR_ROW_MM + gap,
|
|
925
|
+
blockMm: 0
|
|
926
|
+
};
|
|
927
|
+
}
|
|
928
|
+
function marginsOf(layout) {
|
|
929
|
+
return {
|
|
930
|
+
rightMm: layout.columnMm === 0 ? 0 : SIDE_GAP_MM + layout.columnMm,
|
|
931
|
+
belowMm: 2 + layout.blockMm + 2.5 + (layout.lines.length - 1) * 3 + 1.5,
|
|
932
|
+
leastHeightMm: layout.columnHeightMm
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* This function gives the space of the SVG of a map around its frame, for the place of the legend of the map. The
|
|
937
|
+
* size of the frame does not change it.
|
|
938
|
+
*
|
|
939
|
+
* - The label font of the options measures the legend texts. With no font, each character is 0.6 of the size of the font.
|
|
940
|
+
* - The SVG of the map is `rightMm` wider and `belowMm` taller than its frame.
|
|
941
|
+
*
|
|
942
|
+
* @throws MapError - The map is not correct, as `checkMap` tells.
|
|
943
|
+
*/
|
|
944
|
+
function mapMargins(map, options = {}) {
|
|
945
|
+
checkMap(map);
|
|
946
|
+
return marginsOf(legendLayout(map, measureFontOf(options)));
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* This function gives the frame with the largest area for a map in one of a list of spaces, and the place of its
|
|
950
|
+
* legend. The SVG of the map with that frame and that place fits that space.
|
|
951
|
+
*
|
|
952
|
+
* - Give one space for each choice of the caller, for example a paper upright and the same paper in landscape.
|
|
953
|
+
* - The scale of the map does not change, so a larger frame shows more ground.
|
|
954
|
+
* - The size of the frame of the map does not change the result.
|
|
955
|
+
* - With two choices of equal area, the first place of the options wins, and then the first space.
|
|
956
|
+
*
|
|
957
|
+
* @throws MapError - The map is not correct, a place or a space is not correct, or no choice leaves space for a frame.
|
|
958
|
+
*/
|
|
959
|
+
function fitFrame(map, spaces, options = {}) {
|
|
960
|
+
checkMap(map);
|
|
961
|
+
for (const { widthMm, heightMm } of spaces) if (![widthMm, heightMm].every((value) => Number.isFinite(value) && value > 0)) throw new MapError("frame", `The space ${widthMm} by ${heightMm} mm is not two finite numbers more than 0`);
|
|
962
|
+
const places = options.places ?? LEGEND_PLACES;
|
|
963
|
+
const font = measureFontOf(options);
|
|
964
|
+
let best;
|
|
965
|
+
for (const place of places) {
|
|
966
|
+
if (!LEGEND_PLACES.includes(place)) throw new MapError("style", `The place of the legend "${String(place)}" is not "below" or "side"`);
|
|
967
|
+
const margins = marginsOf(legendLayout({
|
|
968
|
+
...map,
|
|
969
|
+
legendPlace: place
|
|
970
|
+
}, font));
|
|
971
|
+
for (const [index, { widthMm, heightMm }] of spaces.entries()) {
|
|
972
|
+
const frameWidth = widthMm - margins.rightMm;
|
|
973
|
+
const frameHeight = heightMm - margins.belowMm;
|
|
974
|
+
if (!(frameWidth > 0 && frameHeight > 0 && frameHeight >= margins.leastHeightMm)) continue;
|
|
975
|
+
if (best === void 0 || frameWidth * frameHeight > best.widthMm * best.heightMm) best = {
|
|
976
|
+
widthMm: frameWidth,
|
|
977
|
+
heightMm: frameHeight,
|
|
978
|
+
legendPlace: place,
|
|
979
|
+
space: index
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
if (best === void 0) throw new MapError("frame", "No space of the list has space for a frame after the legend");
|
|
984
|
+
return best;
|
|
985
|
+
}
|
|
986
|
+
/** This function gives the lines of the attribution block: the scale, the projection and each source one time. */
|
|
987
|
+
function attributionLines(map) {
|
|
988
|
+
const lines = [`Scale 1:${thousands(map.frame.scale)} at the center. Projection: ${map.frame.projection.name}.`];
|
|
989
|
+
const seen = /* @__PURE__ */ new Set();
|
|
990
|
+
for (const { source } of map.layers) {
|
|
991
|
+
const line = `Data: ${source.title}. License: ${source.license}.${source.url === void 0 ? "" : ` ${source.url}`}${source.date === void 0 ? "" : ` Date: ${source.date}.`}`;
|
|
992
|
+
if (seen.has(line)) continue;
|
|
993
|
+
seen.add(line);
|
|
994
|
+
lines.push(line);
|
|
995
|
+
}
|
|
996
|
+
return lines;
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* This function gives the SVG of a map. The units of the SVG are millimetres, for a print at the scale of the frame.
|
|
1000
|
+
*
|
|
1001
|
+
* - The map is at the top. Below it are the scale bars, the legend and the attribution block.
|
|
1002
|
+
* - With the place `side`, the scale bars and the legend are in a column at the right of the frame. The attribution
|
|
1003
|
+
* block stays below.
|
|
1004
|
+
* - The layers are in their sequence, from the bottom to the top. The frame clips each layer.
|
|
1005
|
+
* - A feature that is not on the frame is not in the SVG.
|
|
1006
|
+
* - Each identifier in the SVG starts with the identifier of the map. Thus two maps can be in one HTML page.
|
|
1007
|
+
* - The labels are above the layers. `placeLabels` tells their places. The group of the labels tells the number of
|
|
1008
|
+
* texts with no place in `data-skipped`.
|
|
1009
|
+
*
|
|
1010
|
+
* @throws MapError - The map is not correct, as `checkMap` tells, or a layer has labels and the options have no font.
|
|
1011
|
+
* @throws GeoError - A position is not correct for the projection.
|
|
1012
|
+
*/
|
|
1013
|
+
function renderMap(map, options = {}) {
|
|
1014
|
+
checkMap(map);
|
|
1015
|
+
const font = labelFontOf(map, options);
|
|
1016
|
+
const view = frameView(map.frame);
|
|
1017
|
+
const { widthMm: w, heightMm: h } = map.frame;
|
|
1018
|
+
const defs = [`<clipPath id="${map.id}-clip"><rect width="${mm(w)}" height="${mm(h)}"/></clipPath>`];
|
|
1019
|
+
const fills = map.layers.map((layer) => {
|
|
1020
|
+
const hatch = layer.style.fill?.hatch;
|
|
1021
|
+
if (hatch === void 0) return void 0;
|
|
1022
|
+
const id = `${map.id}-${layer.id}-hatch`;
|
|
1023
|
+
defs.push(hatchPattern(id, hatch));
|
|
1024
|
+
return `url(#${id})`;
|
|
1025
|
+
});
|
|
1026
|
+
const features = map.layers.map((layer) => featuresOf(layer, map.frame));
|
|
1027
|
+
const layers = map.layers.map((layer, i) => {
|
|
1028
|
+
const body = features[i].map((feature) => drawGeometry(feature.geometry, layer.style, view, fills[i])).join("");
|
|
1029
|
+
return `<g id="${map.id}-${layer.id}">${body}</g>`;
|
|
1030
|
+
});
|
|
1031
|
+
const labels = font === void 0 ? "" : labelsSvg(placementOf(map, features, view, font), font);
|
|
1032
|
+
const layout = legendLayout(map, measureFontOf(options));
|
|
1033
|
+
const side = layout.columnMm > 0;
|
|
1034
|
+
const { bars, lines } = layout;
|
|
1035
|
+
const top = (side ? Math.max(h, layout.columnHeightMm) : h) + 2;
|
|
1036
|
+
const sideX = w + SIDE_GAP_MM;
|
|
1037
|
+
const maxMeters = (side ? layout.columnMm - SCALE_LABEL_MM : .3 * w) / view.mmPerMeter;
|
|
1038
|
+
const scaleBars = bars.map((unit, i) => {
|
|
1039
|
+
const length = scaleBarLength(maxMeters, unit);
|
|
1040
|
+
return side ? scaleBarSvg(sideX, SIDE_TOP_MM + i * SCALE_BAR_ROW_MM, length, view.mmPerMeter) : scaleBarSvg(.5, top + i * SCALE_BAR_ROW_MM, length, view.mmPerMeter);
|
|
1041
|
+
}).join("");
|
|
1042
|
+
const legendLayers = map.layers.flatMap((layer, i) => layer.legend === void 0 ? [] : [{
|
|
1043
|
+
layer,
|
|
1044
|
+
fill: fills[i]
|
|
1045
|
+
}]);
|
|
1046
|
+
const columnWidth = w * .275;
|
|
1047
|
+
const sideTop = SIDE_TOP_MM + bars.length * SCALE_BAR_ROW_MM + (bars.length > 0 ? SIDE_GROUP_GAP_MM : 0);
|
|
1048
|
+
const legend = legendLayers.map(({ layer, fill }, i) => {
|
|
1049
|
+
const x = side ? sideX : w * .45 + i % 2 * columnWidth;
|
|
1050
|
+
const y = side ? sideTop + i * SCALE_BAR_ROW_MM : top + Math.floor(i / 2) * SCALE_BAR_ROW_MM - 1;
|
|
1051
|
+
return `${swatch(layer.style, x, y, fill)}<text x="${mm(x + LEGEND_TEXT_X_MM)}" y="${mm(y + 2.9)}" font-size="${LEGEND_TEXT_MM}">${escapeHtml(layer.legend)}</text>`;
|
|
1052
|
+
}).join("");
|
|
1053
|
+
const firstLine = top + layout.blockMm + 2.5;
|
|
1054
|
+
const attribution = lines.map((line, i) => `<text x="0.5" y="${mm(firstLine + i * 3)}" font-size="2.2">${escapeHtml(line)}</text>`).join("");
|
|
1055
|
+
const total = firstLine + (lines.length - 1) * 3 + 1.5;
|
|
1056
|
+
const width = side ? sideX + layout.columnMm : w;
|
|
1057
|
+
const arrow = map.northArrow === false ? "" : northArrowSvg(w - 6.5, 6.5, view.northDegrees);
|
|
1058
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${mm(width)}mm" height="${mm(total)}mm" viewBox="0 0 ${mm(width)} ${mm(total)}" role="img" aria-label="${escapeAttribute(map.title)}" font-family="sans-serif"><title>${escapeHtml(map.title)}</title><defs>${defs.join("")}</defs><rect width="${mm(width)}" height="${mm(total)}" fill="#ffffff"/><g clip-path="url(#${map.id}-clip)">${layers.join("")}</g>${labels}<rect width="${mm(w)}" height="${mm(h)}" fill="none" stroke="#000000" stroke-width="0.3"/>${arrow}<g class="legend">${scaleBars}${legend}</g><g class="attribution">${attribution}</g></svg>`;
|
|
1059
|
+
}
|
|
1060
|
+
export { MapError, SCALE_BAR_ROW_MM, attributionLines, checkFilter, checkFrame, checkLabelRule, checkMap, checkStyle, fitFrame, frameBBox, frameView, geometryKind, grayColor, hatchPattern, labelText, labelsSvg, mapLabels, mapMargins, matchesFilter, mm, niceNumber, northArrowSvg, placeLabels, pointSymbol, renderMap, scaleBarLength, scaleBarSvg, strokeAttributes };
|
|
1061
|
+
|
|
1062
|
+
//# sourceMappingURL=index.js.map
|