@mark1russell7/cartography 0.0.0-bootstrap.0 → 0.1.0
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 +90 -1
- package/dist/index.d.ts +377 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +949 -0
- package/dist/index.js.map +1 -0
- package/package.json +58 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,949 @@
|
|
|
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 ID = /^[a-z][a-z0-9-]*$/;
|
|
721
|
+
function checkId(id, what) {
|
|
722
|
+
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`);
|
|
723
|
+
}
|
|
724
|
+
function checkSource(source, layer) {
|
|
725
|
+
if (source === void 0 || typeof source !== "object") throw new MapError("source", `The layer "${layer}" has no source`);
|
|
726
|
+
if (typeof source.title !== "string" || source.title.trim() === "") throw new MapError("source", `The source of the layer "${layer}" has no title`);
|
|
727
|
+
if (typeof source.license !== "string" || source.license.trim() === "") throw new MapError("source", `The source of the layer "${layer}" has no license`);
|
|
728
|
+
}
|
|
729
|
+
/**
|
|
730
|
+
* This function examines a map. It refuses a frame, an identifier, a style, a filter or a source that is not correct.
|
|
731
|
+
* Each layer must have a source with a title and a license, so the attribution block names each source of the map.
|
|
732
|
+
*
|
|
733
|
+
* @throws MapError - The code tells the reason.
|
|
734
|
+
*/
|
|
735
|
+
function checkMap(map) {
|
|
736
|
+
checkId(map.id, "map");
|
|
737
|
+
frameView(map.frame);
|
|
738
|
+
const ids = /* @__PURE__ */ new Set();
|
|
739
|
+
for (const layer of map.layers) {
|
|
740
|
+
checkId(layer.id, "layer");
|
|
741
|
+
if (ids.has(layer.id)) throw new MapError("id", `Two layers have the identifier "${layer.id}"`);
|
|
742
|
+
ids.add(layer.id);
|
|
743
|
+
checkSource(layer.source, layer.id);
|
|
744
|
+
checkStyle(layer.style, layer.id);
|
|
745
|
+
if (layer.filter !== void 0) checkFilter(layer.filter, `layer "${layer.id}" filter`);
|
|
746
|
+
if (layer.label !== void 0) checkLabelRule(layer.label, layer.id);
|
|
747
|
+
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`);
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/** The box of the points on the paper that a feature uses. */
|
|
751
|
+
var PaperBox = class {
|
|
752
|
+
minX = Number.POSITIVE_INFINITY;
|
|
753
|
+
minY = Number.POSITIVE_INFINITY;
|
|
754
|
+
maxX = Number.NEGATIVE_INFINITY;
|
|
755
|
+
maxY = Number.NEGATIVE_INFINITY;
|
|
756
|
+
add(point) {
|
|
757
|
+
this.minX = Math.min(this.minX, point.x);
|
|
758
|
+
this.minY = Math.min(this.minY, point.y);
|
|
759
|
+
this.maxX = Math.max(this.maxX, point.x);
|
|
760
|
+
this.maxY = Math.max(this.maxY, point.y);
|
|
761
|
+
}
|
|
762
|
+
/** It tells if the box touches the frame, with a margin in millimetres. */
|
|
763
|
+
touches(frame, margin) {
|
|
764
|
+
return this.maxX >= -margin && this.minX <= frame.widthMm + margin && this.maxY >= -margin && this.minY <= frame.heightMm + margin;
|
|
765
|
+
}
|
|
766
|
+
};
|
|
767
|
+
function paperOf(position, view) {
|
|
768
|
+
return view.toPaper({
|
|
769
|
+
lat: position[1],
|
|
770
|
+
lon: position[0]
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
function linePath(positions, view, box, close) {
|
|
774
|
+
let d = "";
|
|
775
|
+
positions.forEach((position, i) => {
|
|
776
|
+
const point = paperOf(position, view);
|
|
777
|
+
box.add(point);
|
|
778
|
+
d += `${i === 0 ? "M" : "L"}${mm(point.x)} ${mm(point.y)}`;
|
|
779
|
+
});
|
|
780
|
+
return close ? `${d}Z` : d;
|
|
781
|
+
}
|
|
782
|
+
/** This function gives the SVG of one geometry with a style. */
|
|
783
|
+
function drawGeometry(geometry, style, view, fill) {
|
|
784
|
+
const frame = view.frame;
|
|
785
|
+
switch (geometry.type) {
|
|
786
|
+
case "Point":
|
|
787
|
+
case "MultiPoint":
|
|
788
|
+
if (style.point === void 0) return "";
|
|
789
|
+
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("");
|
|
790
|
+
case "LineString":
|
|
791
|
+
case "MultiLineString": {
|
|
792
|
+
if (style.stroke === void 0) return "";
|
|
793
|
+
const box = new PaperBox();
|
|
794
|
+
const d = (geometry.type === "LineString" ? [geometry.coordinates] : geometry.coordinates).map((line) => linePath(line, view, box, false)).join("");
|
|
795
|
+
if (!box.touches(frame, style.stroke.widthMm)) return "";
|
|
796
|
+
return `<path d="${d}" fill="none" ${strokeAttributes(style.stroke)}/>`;
|
|
797
|
+
}
|
|
798
|
+
case "Polygon":
|
|
799
|
+
case "MultiPolygon": {
|
|
800
|
+
const box = new PaperBox();
|
|
801
|
+
const d = (geometry.type === "Polygon" ? [geometry.coordinates] : geometry.coordinates).flatMap((rings) => rings.map((ring) => linePath(ring, view, box, true))).join("");
|
|
802
|
+
if (!box.touches(frame, style.stroke?.widthMm ?? 0)) return "";
|
|
803
|
+
const stroke = style.stroke === void 0 ? `stroke="none"` : strokeAttributes(style.stroke);
|
|
804
|
+
let svg = "";
|
|
805
|
+
if (style.fill?.gray !== void 0) svg += `<path d="${d}" fill="${grayColor(style.fill.gray)}" fill-rule="evenodd" stroke="none"/>`;
|
|
806
|
+
svg += `<path d="${d}" fill="${fill ?? "none"}" fill-rule="evenodd" ${stroke}/>`;
|
|
807
|
+
return svg;
|
|
808
|
+
}
|
|
809
|
+
case "GeometryCollection": return geometry.geometries.map((item) => drawGeometry(item, style, view, fill)).join("");
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
/** This function gives the features of a layer after its filter and its simplification. */
|
|
813
|
+
function featuresOf(layer, frame) {
|
|
814
|
+
const kept = layer.features.filter((feature) => feature.geometry !== null && (layer.filter === void 0 || matchesFilter(layer.filter, feature)));
|
|
815
|
+
if (layer.simplifyMm === void 0) return kept;
|
|
816
|
+
const areas = kept.flatMap((feature, i) => feature.geometry?.type === "Polygon" || feature.geometry?.type === "MultiPolygon" ? [i] : []);
|
|
817
|
+
if (areas.length === 0) return kept;
|
|
818
|
+
const simplified = simplifyRegions(areas.map((i) => kept[i].geometry), layer.simplifyMm * frame.scale / 1e6);
|
|
819
|
+
const result = [...kept];
|
|
820
|
+
areas.forEach((index, j) => {
|
|
821
|
+
result[index] = {
|
|
822
|
+
...kept[index],
|
|
823
|
+
geometry: simplified[j]
|
|
824
|
+
};
|
|
825
|
+
});
|
|
826
|
+
return result;
|
|
827
|
+
}
|
|
828
|
+
/** The middle of the north arrow, from the top right corner of the frame, and the half size of its box, in millimetres. */
|
|
829
|
+
const NORTH_ARROW = {
|
|
830
|
+
inset: 6.5,
|
|
831
|
+
half: 4.7
|
|
832
|
+
};
|
|
833
|
+
function placementOf(map, features, view, font) {
|
|
834
|
+
const obstacles = map.northArrow === false ? [] : [{
|
|
835
|
+
x: map.frame.widthMm - NORTH_ARROW.inset,
|
|
836
|
+
y: NORTH_ARROW.inset,
|
|
837
|
+
half: NORTH_ARROW.half
|
|
838
|
+
}];
|
|
839
|
+
return placeLabels(map.layers.map((layer, i) => ({
|
|
840
|
+
id: layer.id,
|
|
841
|
+
features: features[i],
|
|
842
|
+
label: layer.label,
|
|
843
|
+
pointSizeMm: layer.style.point?.sizeMm
|
|
844
|
+
})), view, font, obstacles);
|
|
845
|
+
}
|
|
846
|
+
function labelFontOf(map, options) {
|
|
847
|
+
const labelled = map.layers.find((layer) => layer.label !== void 0);
|
|
848
|
+
if (labelled === void 0) return void 0;
|
|
849
|
+
const font = options.labelFont;
|
|
850
|
+
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`);
|
|
851
|
+
return font;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* This function gives the labels of a map with their places, and the texts with no place. `renderMap` draws the same
|
|
855
|
+
* labels.
|
|
856
|
+
*
|
|
857
|
+
* @throws MapError - The map is not correct, as `checkMap` tells, or a layer has labels and the options have no font.
|
|
858
|
+
*/
|
|
859
|
+
function mapLabels(map, options = {}) {
|
|
860
|
+
checkMap(map);
|
|
861
|
+
const font = labelFontOf(map, options);
|
|
862
|
+
if (font === void 0) return {
|
|
863
|
+
placed: [],
|
|
864
|
+
skipped: []
|
|
865
|
+
};
|
|
866
|
+
return placementOf(map, map.layers.map((layer) => featuresOf(layer, map.frame)), frameView(map.frame), font);
|
|
867
|
+
}
|
|
868
|
+
/** This function gives the swatch of a layer in the legend, with its top left corner at a point. */
|
|
869
|
+
function swatch(style, x, y, fill) {
|
|
870
|
+
if (style.point !== void 0) return pointSymbol(style.point, x + 3, y + 1.75);
|
|
871
|
+
if (style.fill !== void 0) {
|
|
872
|
+
const stroke = style.stroke === void 0 ? `stroke="#000000" stroke-width="0.1"` : strokeAttributes(style.stroke);
|
|
873
|
+
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}/>`;
|
|
874
|
+
}
|
|
875
|
+
return `<path d="M${mm(x)} ${mm(y + 1.75)}L${mm(x + 6)} ${mm(y + 1.75)}" ${strokeAttributes(style.stroke)}/>`;
|
|
876
|
+
}
|
|
877
|
+
function thousands(value) {
|
|
878
|
+
return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
879
|
+
}
|
|
880
|
+
/** This function gives the lines of the attribution block: the scale, the projection and each source one time. */
|
|
881
|
+
function attributionLines(map) {
|
|
882
|
+
const lines = [`Scale 1:${thousands(map.frame.scale)} at the center. Projection: ${map.frame.projection.name}.`];
|
|
883
|
+
const seen = /* @__PURE__ */ new Set();
|
|
884
|
+
for (const { source } of map.layers) {
|
|
885
|
+
const line = `Data: ${source.title}. License: ${source.license}.${source.url === void 0 ? "" : ` ${source.url}`}${source.date === void 0 ? "" : ` Date: ${source.date}.`}`;
|
|
886
|
+
if (seen.has(line)) continue;
|
|
887
|
+
seen.add(line);
|
|
888
|
+
lines.push(line);
|
|
889
|
+
}
|
|
890
|
+
return lines;
|
|
891
|
+
}
|
|
892
|
+
/**
|
|
893
|
+
* This function gives the SVG of a map. The units of the SVG are millimetres, for a print at the scale of the frame.
|
|
894
|
+
*
|
|
895
|
+
* - The map is at the top. Below it are the scale bars, the legend and the attribution block.
|
|
896
|
+
* - The layers are in their sequence, from the bottom to the top. The frame clips each layer.
|
|
897
|
+
* - A feature that is not on the frame is not in the SVG.
|
|
898
|
+
* - Each identifier in the SVG starts with the identifier of the map. Thus two maps can be in one HTML page.
|
|
899
|
+
* - The labels are above the layers. `placeLabels` tells their places. The group of the labels tells the number of
|
|
900
|
+
* texts with no place in `data-skipped`.
|
|
901
|
+
*
|
|
902
|
+
* @throws MapError - The map is not correct, as `checkMap` tells, or a layer has labels and the options have no font.
|
|
903
|
+
* @throws GeoError - A position is not correct for the projection.
|
|
904
|
+
*/
|
|
905
|
+
function renderMap(map, options = {}) {
|
|
906
|
+
checkMap(map);
|
|
907
|
+
const font = labelFontOf(map, options);
|
|
908
|
+
const view = frameView(map.frame);
|
|
909
|
+
const { widthMm: w, heightMm: h } = map.frame;
|
|
910
|
+
const defs = [`<clipPath id="${map.id}-clip"><rect width="${mm(w)}" height="${mm(h)}"/></clipPath>`];
|
|
911
|
+
const fills = map.layers.map((layer) => {
|
|
912
|
+
const hatch = layer.style.fill?.hatch;
|
|
913
|
+
if (hatch === void 0) return void 0;
|
|
914
|
+
const id = `${map.id}-${layer.id}-hatch`;
|
|
915
|
+
defs.push(hatchPattern(id, hatch));
|
|
916
|
+
return `url(#${id})`;
|
|
917
|
+
});
|
|
918
|
+
const features = map.layers.map((layer) => featuresOf(layer, map.frame));
|
|
919
|
+
const layers = map.layers.map((layer, i) => {
|
|
920
|
+
const body = features[i].map((feature) => drawGeometry(feature.geometry, layer.style, view, fills[i])).join("");
|
|
921
|
+
return `<g id="${map.id}-${layer.id}">${body}</g>`;
|
|
922
|
+
});
|
|
923
|
+
const labels = font === void 0 ? "" : labelsSvg(placementOf(map, features, view, font), font);
|
|
924
|
+
const top = h + 2;
|
|
925
|
+
const units = map.scaleBar ?? "both";
|
|
926
|
+
const bars = units === "none" ? [] : units === "both" ? ["metric", "imperial"] : [units];
|
|
927
|
+
const maxMeters = .3 * w / view.mmPerMeter;
|
|
928
|
+
const scaleBars = bars.map((unit, i) => scaleBarSvg(.5, top + i * SCALE_BAR_ROW_MM, scaleBarLength(maxMeters, unit), view.mmPerMeter)).join("");
|
|
929
|
+
const legendLayers = map.layers.flatMap((layer, i) => layer.legend === void 0 ? [] : [{
|
|
930
|
+
layer,
|
|
931
|
+
fill: fills[i]
|
|
932
|
+
}]);
|
|
933
|
+
const columnWidth = w * .275;
|
|
934
|
+
const legend = legendLayers.map(({ layer, fill }, i) => {
|
|
935
|
+
const x = w * .45 + i % 2 * columnWidth;
|
|
936
|
+
const y = top + Math.floor(i / 2) * SCALE_BAR_ROW_MM - 1;
|
|
937
|
+
return `${swatch(layer.style, x, y, fill)}<text x="${mm(x + 7.5)}" y="${mm(y + 2.9)}" font-size="2.4">${escapeHtml(layer.legend)}</text>`;
|
|
938
|
+
}).join("");
|
|
939
|
+
const blockHeight = Math.max(bars.length, Math.ceil(legendLayers.length / 2)) * SCALE_BAR_ROW_MM;
|
|
940
|
+
const lines = attributionLines(map);
|
|
941
|
+
const firstLine = top + blockHeight + 2.5;
|
|
942
|
+
const attribution = lines.map((line, i) => `<text x="0.5" y="${mm(firstLine + i * 3)}" font-size="2.2">${escapeHtml(line)}</text>`).join("");
|
|
943
|
+
const total = firstLine + (lines.length - 1) * 3 + 1.5;
|
|
944
|
+
const arrow = map.northArrow === false ? "" : northArrowSvg(w - 6.5, 6.5, view.northDegrees);
|
|
945
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${mm(w)}mm" height="${mm(total)}mm" viewBox="0 0 ${mm(w)} ${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(w)}" 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>`;
|
|
946
|
+
}
|
|
947
|
+
export { MapError, SCALE_BAR_ROW_MM, attributionLines, checkFilter, checkFrame, checkLabelRule, checkMap, checkStyle, frameBBox, frameView, geometryKind, grayColor, hatchPattern, labelText, labelsSvg, mapLabels, matchesFilter, mm, niceNumber, northArrowSvg, placeLabels, pointSymbol, renderMap, scaleBarLength, scaleBarSvg, strokeAttributes };
|
|
948
|
+
|
|
949
|
+
//# sourceMappingURL=index.js.map
|