@mark1russell7/cartography
v0.1.7
Published
Maps as data: a frame, layers with filters and black and white styles, and a render to SVG in millimetres with a scale bar, a north arrow, a legend and the attribution of each source.
Maintainers
Readme
@mark1russell7/cartography
Maps as data for print and screen. A map is a frame, layers from the bottom to the top, and its marks. The render gives an SVG in millimetres, for a print at the scale of the frame. The core names no topic. An add-on gives the layers and the styles of a topic, for example @mark1russell7/cartography-emergency.
import { renderMap, type MapDocument } from "@mark1russell7/cartography";
import { azimuthalEquidistant } from "@mark1russell7/geo/projection";
const center = { lat: 45, lon: 10 };
const map: MapDocument = {
id: "town",
title: "The roads of the town",
frame: { projection: azimuthalEquidistant(center), center, scale: 24000, widthMm: 180, heightMm: 240 },
layers: [
{
id: "roads",
features: roads, // GeoJSON features, positions [lon, lat] on WGS84
filter: { property: "highway", in: ["primary", "secondary"] },
style: { stroke: { widthMm: 0.6 } },
source: { title: "© OpenStreetMap contributors", license: "ODbL 1.0", url: "https://www.openstreetmap.org/copyright" },
legend: "Main road",
},
],
};
const svg = renderMap(map);The parts of a map
| Part | Type | Rules |
| --- | --- | --- |
| Frame | Frame | A projection, a center, the denominator of the scale, and the width and the height on the paper in millimetres. |
| Layer | Layer | Features, a filter, a style, a source and a legend text. The tolerance simplifyMm simplifies the areas. |
| Filter | Filter | Data, so a map can be JSON: all, any, not, property with in or exists, and geometry. |
| Style | Style | Black, white and gray only: lines with dashes, areas with gray levels and hatches, and point symbols. |
| Source | Source | A title and a license. Each layer must have a source. The attribution block names each source one time. |
| Edge texts | edges | A text at the middle of an edge of the frame, for example the name of the neighbor page in an atlas. |
The functions
| Function | Result |
| --- | --- |
| renderMap(map, options) | The SVG of the map, with the scale bars, the legend, the north arrow, the labels and the attribution block. |
| checkMap(map) | Nothing. It throws a MapError for a map that is not correct. |
| frameView(frame) | The functions between the Earth and the paper, and the direction of north. |
| frameBBox(frame) | The box on the Earth around the frame, for a fetch of the data of a map. |
| frameAround(points, options) | The frame with the largest scale that shows each point inside the margin. The option roundScale rounds the scale up. |
| niceScale(value) | The smallest round scale that is not less than the value, from NICE_SCALE_STEPS. |
| geometryPath(view, geometry, options) | The SVG path data of a line or an area on the paper of a frame. |
| matchesFilter(filter, feature) | true when the feature matches the filter. |
| checkFilter(value) | Nothing. It throws a MapError for a value that is not a Filter. |
| attributionLines(map) | The lines of the attribution block: the scale, the projection and each source. |
| frameAttribution(frame, sources, options) | The same lines for a frame and a list of sources, for a map that a page draws itself. The option scale: false leaves out the scale. |
| scaleBarSvg(x, y, length, mmPerMeter, paint) | The SVG of a scale bar. The paint sets its ink and paper colors. The default is black on white. |
| northArrowSvg(x, y, northDegrees, paint) | The SVG of a north arrow. The paint sets its colors, as for the scale bar. |
| scaleBarLength(meters, units) | The longest round length of a scale bar that is not longer than a length on the ground. |
| mapLabels(map, options) | The labels of the map with their places, and the texts with no place. |
| mapMargins(map, options) | The space of the SVG around the frame: the column at the right, the block below, and the least height of the frame. |
| fitFrame(map, spaces, options) | The frame with the largest area in one of a list of spaces, for example a paper, and the place of its legend. |
| placeLabels(layers, view, font) | The places of the labels of the layers, with no overlap, inside the frame. |
| labelText(rule, feature) | The text of the label of a feature, or undefined. |
| atlasPages(plan) | The pages of an atlas of a large area at one scale, with the names of their neighbor pages. |
| atlasOutlines(atlas) | The outline of each page of an atlas as a polygon feature, for an index map. |
| atlasIndexFrame(atlas, widthMm, heightMm) | The frame of an index map that shows all the pages of an atlas. |
Labels
A layer with a label rule shows the names of its features. The labels do not overlap, and each label is inside the frame.
import { readFileSync } from "node:fs";
import { measureWidth, readFont } from "@mark1russell7/typeset/fonts";
const font = readFont(readFileSync("LiberationSans-Regular.ttf"));
const labelFont = {
family: '"Liberation Sans", Arial, sans-serif',
measure: (text: string, sizeMm: number) => measureWidth(font, text, sizeMm),
};
const roads = { ...layer, label: { properties: ["ref", "name"], sizeMm: 2.5, repeatMm: 80 } };
const svg = renderMap({ ...map, layers: [roads] }, { labelFont });- The core has no font tables. The caller gives the font family and a function that measures a text in millimetres.
- Use the same font for the print. Liberation Sans has the same widths as Arial.
- A point label goes to the first free place of 8 places around its symbol.
- A line label goes along an almost straight part of the line, near its middle.
repeatMmgives more labels on a long line. - An area label goes to the middle of the area, when the area has the full box of the text.
- A layer with a lower
prioritygets its places first. With the same priority, a higher layer is first. - The point symbols, the north arrow and the edge texts are obstacles. No label covers them.
- The render puts the labels above the layers, in black with a white halo.
- A text with no free place is in the list
skippedofmapLabels. The SVG gives the count indata-skipped.
Rules
- The scale of the frame is the true scale at the center. Use
azimuthalEquidistantfor a map of a small area. - Web Mercator changes its scale with the latitude. On the ellipsoid, it also changes its scale with the direction: at 45 degrees, by approximately 0.34 %.
- The render removes a feature that is not on the frame, and the frame clips each layer.
- Each identifier in the SVG starts with the identifier of the map. Thus two maps can be in one HTML page.
- The simplification uses
simplifyRegionsof@mark1russell7/geo. A tolerance of 0.2 mm on the paper at 1:24,000 is 4.8 m on the ground. - Each refusal is a
MapErrorwith a code:frame,id,filter,style,sourceorlabel.
License
MIT
A map that fills a paper
fitFrame gives the frame with the largest area in one of a list of spaces, and the place of the legend. The scale does not change, so a larger frame shows more ground.
// A paper of 24 by 36 in with a margin of 0.5 in, upright and in landscape, below a heading of 50 mm.
const spaces = [{ widthMm: 584.2, heightMm: 889 - 50 }, { widthMm: 889, heightMm: 584.2 - 50 }];
const fit = fitFrame(map, spaces, { labelFont });
const frame = { ...map.frame, widthMm: fit.widthMm, heightMm: fit.heightMm };
const svg = renderMap({ ...map, frame, legendPlace: fit.legendPlace }, { labelFont });- The place
belowputs the scale bars and the legend in two columns below the frame. This is the default. - The place
sideputs them in one column at the right of the frame. The attribution block stays below the frame. mapMarginsgives the space around the frame for each place. The label font measures the legend texts.fit.spaceis the index of the space of the frame. In this example, the value 1 tells to print the map in landscape.
A frame for a box on the Earth
With no heightMm, frameAround fits the width only, and the height follows from the points. For a box in degrees, give its 4 corners and the middles of its north and south edges. An edge of the box is a curve on most planes. geometryPath gives the SVG path data of a geometry on the frame.
// A made-up box of approximately 8 km by 4.4 km, on a map of 180 mm width.
const box = { south: 44.98, west: 9.95, north: 45.02, east: 10.05 };
const middle = (box.west + box.east) / 2;
const points = [
{ lat: box.south, lon: box.west }, { lat: box.south, lon: box.east },
{ lat: box.north, lon: box.west }, { lat: box.north, lon: box.east },
{ lat: box.north, lon: middle }, { lat: box.south, lon: middle },
];
const frame = frameAround(points, { projection: azimuthalEquidistant, widthMm: 180, roundScale: false });
const d = geometryPath(frameView(frame), { type: "Polygon", coordinates: [[[9.97, 44.99], [10.03, 44.99], [10.03, 45.01], [9.97, 44.99]]] });
const svg = `<svg viewBox="0 0 ${frame.widthMm} ${frame.heightMm}"><path d="${d}" fill="none" stroke="black"/></svg>`;- The center of the frame is the middle of the box of the points in degrees, not on the plane. The option
centersets a different center. - The frame has the center at its middle. The point that is farthest from the center in x touches a side edge.
- For points that are symmetric about the center, a point touches each of the two side edges.
- The height is the reach of the points in y on the two sides of the center, with the margins. It is rounded up to a whole millimetre.
- With
roundScale, the default, the scale goes up to a round value. Then the points do not fill the width. - Each ring of a polygon is
Mand its first point,Land each next point, andZ. A line has noZ. A point gives no path data. - The values are in millimetres from the top left corner of the frame, with 2 decimals. The option
decimalschanges the number. renderMapuses the same path data for its lines and areas.geometryPathdoes not clip to the frame.
The marks of a screen map
A page that draws its own map, for example with colors and events, can add the marks of a print map. Give the marks a paint with currentColor. Then the CSS of the page sets their colors in its light and dark theme.
const view = frameView(frame);
const paint = { ink: "currentColor", paper: "none" };
const length = scaleBarLength((0.3 * frame.widthMm) / view.mmPerMeter, "metric");
const bar = scaleBarSvg(4, frame.heightMm - 6, length, view.mmPerMeter, paint);
const arrow = northArrowSvg(frame.widthMm - 6.5, 6.5, view.northDegrees, paint);
const lines = frameAttribution(frame, [{ title: "Made-up test data", license: "CC0 1.0" }], { scale: false });- The ink is the color of the lines, the texts and the dark parts. The paper is the color of the light parts. The value
nonegives light parts with no fill. - A color goes into an SVG attribute with escapes. An empty color throws a
MapErrorwith the codestyle. - With no paint, the marks are the same as the marks of
renderMap. - A screen map changes its size with the window, so the scale of the frame is not true on the screen. The option
scale: falseleaves it out. The scale bar stays correct. frameAttributionnames each source one time, in the sequence of the list. A source with no title or no license throws aMapErrorwith the codesource.
An atlas of a large area
An area that is too large for one page at a good scale goes on the pages of an atlas. atlasPages gives a grid of frames on the plane of one projection.
// A made-up center. The circle of 25 km at 1:63,360 on pages with a map of 190 by 230 mm.
const center = { lat: 45, lon: 10 };
const atlas = atlasPages({ projection: azimuthalEquidistant(center), center, radiusMeters: 25_000, scale: 63_360, widthMm: 190, heightMm: 230 });
for (const page of atlas.pages) {
// page.id is the name of the page, for example "C2". page.neighbors.right is the name of the page at its right edge.
const edges = Object.fromEntries(Object.entries(page.neighbors).map(([edge, id]) => [edge, `Page ${id}`]));
const svg = renderMap({ ...map, frame: page.frame, edges }, { labelFont });
}
const index = atlasIndexFrame(atlas, 190, 120);
const pagesLayer = { id: "pages", features: atlasOutlines(atlas), style: outlineStyle, source, label: { properties: ["id"], sizeMm: 4 } };- The grid has its middle at the center of the area. It has the smallest number of columns and rows that shows the full circle.
- Neighbor pages share a strip of
overlapMmat their common edge. The default is 10 mm. - A page of the grid that shows no part of the circle is not in the atlas. Its neighbors do not name it.
- The columns have the letters A, B and the next letters from the west. The rows have the numbers 1, 2 and the next numbers from the north.
- Each page has the scale of the plan at its own center. With one azimuthal equidistant projection over 50 km, the edges of neighbor pages agree to 0.01 mm.
- The field
edgesof a map puts a text at the middle of each edge of the frame, with an arrow. No label covers it. atlasOutlinesgives each outline with the name of its page in the propertyid. A label rule can show the names on the index map.
