mirror of
https://github.com/lrnselfreliance/wrolpi.git
synced 2026-11-22 07:56:18 -05:00
The standalone map viewer draws overlays, as the map does (#966)
The standalone viewer (port 8084) drew basemaps only: a map file which is not a basemap was skipped. It now offers each overlay in its layer panel, hidden until turned on, with a checkbox per layer, draws it with the style beside it when there is one, and shows a feature's attributes on a click. The overlay logic is the map viewer's own. It moved to dependency-free modules (app/src/map-shared) which a browser can load as they are; the standalone viewer, which has no build step, loads copies of them from modules/map/static/js. A test fails while a copy differs from its module (`npm run sync:map-shared` makes the copies). What differs between the viewers is passed in: where a map file and its style are fetched from, and whether a layer can be checked before MapLibre is given it. The standalone viewer cannot check a layer first, so it adds an overlay's layers to the map one at a time once the style has loaded: MapLibre refuses a whole style over one layer it cannot draw, but only that layer when it is added by itself. The API also names a style by its path within the map directory, which is what the standalone viewer is served. Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
113e70a402
commit
177d0dba4b
15 changed files with 1754 additions and 506 deletions
|
|
@ -1,153 +1,15 @@
|
|||
// A style a person put beside a PMTiles file says how that overlay is drawn, in place of the generic
|
||||
// colors. It is an ordinary MapLibre style document written for some other map, so only what is
|
||||
// safe and meaningful here is taken from it: the layers which draw this file. Its sources, sprite
|
||||
// and glyph URLs are never used, so a style cannot make the map ask another host for anything.
|
||||
// The map viewer's side of the sidecar style code: the shared logic
|
||||
// (../map-shared/overlayStyle.js) with this app's URLs, and with each layer checked by MapLibre's
|
||||
// style validator before it reaches the map.
|
||||
|
||||
import {validateStyleMin} from "@maplibre/maplibre-gl-style-spec";
|
||||
import {mediaUrl, overlaySourceId} from "./mapOverlays";
|
||||
import * as shared from "../map-shared/overlayStyle.js";
|
||||
import {MAP_URLS} from "./mapOverlays";
|
||||
|
||||
// The fonts the map has glyphs for (modules/map/static/fonts). The map has one glyph URL, so a
|
||||
// style's own fonts cannot be loaded; each is replaced by the nearest of these.
|
||||
const FONT_REGULAR = "Noto Sans Regular";
|
||||
const FONT_MEDIUM = "Noto Sans Medium";
|
||||
const FONT_ITALIC = "Noto Sans Italic";
|
||||
export * from "../map-shared/overlayStyle.js";
|
||||
|
||||
// Properties whose value names an image of the sprite.
|
||||
const IMAGE_PROPERTIES = {
|
||||
layout: ["icon-image"],
|
||||
paint: ["fill-pattern", "line-pattern", "fill-extrusion-pattern"],
|
||||
};
|
||||
|
||||
// Expression operators a `text-font` value can start with; anything else is a plain list of fonts.
|
||||
const FONT_EXPRESSIONS = new Set(["literal", "match", "case", "step", "coalesce", "let", "var", "get"]);
|
||||
|
||||
export function bundledFont(name) {
|
||||
if (/italic|oblique/i.test(name)) return FONT_ITALIC;
|
||||
if (/bold|medium|black|heavy/i.test(name)) return FONT_MEDIUM;
|
||||
return FONT_REGULAR;
|
||||
}
|
||||
|
||||
const fontList = fonts => [...new Set(fonts.map(f => bundledFont(String(f))))];
|
||||
|
||||
// Inside an expression only a `literal` list is a list of fonts; other lists are not (the labels
|
||||
// of a `match` are a list of strings too).
|
||||
function adaptFontExpression(value) {
|
||||
if (!Array.isArray(value)) return value;
|
||||
if (value[0] === "literal" && Array.isArray(value[1])) return ["literal", fontList(value[1])];
|
||||
return value.map(adaptFontExpression);
|
||||
}
|
||||
|
||||
// Replace every font a `text-font` value names, as a plain list or as the literal lists of an
|
||||
// expression.
|
||||
function adaptFonts(value) {
|
||||
if (!Array.isArray(value)) return value;
|
||||
return FONT_EXPRESSIONS.has(value[0]) ? adaptFontExpression(value) : fontList(value);
|
||||
}
|
||||
|
||||
// A `text-field` can set the font of a part of the text (the options of a `format` section); those
|
||||
// fonts are replaced too.
|
||||
function adaptTextFieldFonts(value) {
|
||||
if (Array.isArray(value)) return value.map(adaptTextFieldFonts);
|
||||
if (value && typeof value === "object") {
|
||||
const options = {};
|
||||
for (const [key, option] of Object.entries(value)) {
|
||||
options[key] = key === "text-font" ? adaptFonts(option) : adaptTextFieldFonts(option);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// The id of an overlay's sprite; MapLibre knows its images as `<sprite id>:<image name>`.
|
||||
export function overlaySpriteId(file) {
|
||||
return overlaySourceId(file);
|
||||
}
|
||||
|
||||
// The sprite sheet of an overlay, as MapLibre asks for it (it appends `@2x` and the extension).
|
||||
export function overlaySpriteUrl(file) {
|
||||
const path = String(file.map_path).split("/").map(encodeURIComponent).join("/");
|
||||
return `${window.location.origin}/api/map/files/sprite/${path}`;
|
||||
}
|
||||
|
||||
const isZoom = value => Array.isArray(value) && value.length === 1 && value[0] === "zoom";
|
||||
|
||||
// An image may be named by a property function (the older form of an expression: an object with
|
||||
// `stops`, or `type: "identity"`). It is rewritten as the expression which gives the same name,
|
||||
// so that the name can be pointed at the overlay's sprite. Returns undefined for a function
|
||||
// this does not know how to rewrite.
|
||||
function imageFunctionExpression(fn) {
|
||||
const fallback = typeof fn.default === "string" ? fn.default : "";
|
||||
if (fn.type === "identity" && typeof fn.property === "string") {
|
||||
return ["coalesce", ["get", fn.property], fallback];
|
||||
}
|
||||
|
||||
const stops = fn.stops;
|
||||
if (!Array.isArray(stops) || !stops.length || !stops.every(i => Array.isArray(i) && i.length === 2)) {
|
||||
return undefined;
|
||||
}
|
||||
const inputs = stops.map(i => i[0]);
|
||||
const outputs = stops.map(i => i[1]);
|
||||
if (!outputs.every(i => typeof i === "string")) return undefined;
|
||||
|
||||
if (fn.type === "categorical") {
|
||||
// One name per value of the property.
|
||||
const labels = inputs.every(i => typeof i === "string") || inputs.every(i => typeof i === "number");
|
||||
if (typeof fn.property !== "string" || !labels || new Set(inputs).size !== inputs.length) return undefined;
|
||||
return ["match", ["get", fn.property], ...stops.flat(), fallback];
|
||||
}
|
||||
if (fn.type !== undefined && fn.type !== "interval") return undefined;
|
||||
if (!inputs.every(i => typeof i === "number") || inputs.some((v, i) => i > 0 && v <= inputs[i - 1])) {
|
||||
return undefined;
|
||||
}
|
||||
// A single stop is one name, whatever the input.
|
||||
if (stops.length === 1) return outputs[0];
|
||||
// One name per range of the zoom, or of a numeric property; below the first stop is the first.
|
||||
const input = fn.property === undefined ? ["zoom"]
|
||||
: typeof fn.property === "string" ? ["to-number", ["get", fn.property], inputs[0]] : undefined;
|
||||
if (!input) return undefined;
|
||||
return ["step", input, outputs[0], ...stops.slice(1).flat()];
|
||||
}
|
||||
|
||||
// Point an image name at the overlay's sprite. The value is wrapped, not rewritten: the strings of
|
||||
// an expression are not all image names (the labels of a `match` are not), but whatever it
|
||||
// evaluates to is. An empty name stays empty: no image. Returns undefined when the value is one
|
||||
// this cannot point at the sprite.
|
||||
function adaptImage(value, spriteId) {
|
||||
if (typeof value === "string") {
|
||||
return value ? `${spriteId}:${value}` : value;
|
||||
}
|
||||
if (value && typeof value === "object" && !Array.isArray(value)) {
|
||||
const expression = imageFunctionExpression(value);
|
||||
return expression === undefined ? undefined : adaptImage(expression, spriteId);
|
||||
}
|
||||
if (!Array.isArray(value)) return undefined;
|
||||
if (value[0] === "step" && isZoom(value[1])) {
|
||||
// The zoom may only be the input of the outermost expression, so each name it chooses
|
||||
// between is wrapped, not the whole.
|
||||
const adapted = value.map((part, index) =>
|
||||
(index >= 2 && index % 2 === 0) ? adaptImage(part, spriteId) : part);
|
||||
return adapted.includes(undefined) ? undefined : adapted;
|
||||
}
|
||||
return ["image", ["let", "wrolpi_image", ["to-string", value],
|
||||
["case", ["==", ["var", "wrolpi_image"], ""], "",
|
||||
["concat", `${spriteId}:`, ["var", "wrolpi_image"]]]]];
|
||||
}
|
||||
|
||||
// The source of the style which is this file: the one the style names for us, else the one most of
|
||||
// the layers which draw this file's layers use.
|
||||
function chooseSource(style, fileLayerIds) {
|
||||
const named = style.metadata?.["wrolpi:source"];
|
||||
if (named) return named;
|
||||
const counts = {};
|
||||
for (const layer of style.layers) {
|
||||
if (layer && layer.source && fileLayerIds.has(layer["source-layer"])) {
|
||||
counts[layer.source] = (counts[layer.source] || 0) + 1;
|
||||
}
|
||||
}
|
||||
return Object.keys(counts).sort((a, b) => counts[b] - counts[a])[0];
|
||||
}
|
||||
|
||||
function validationErrors(layer, source, spriteId) {
|
||||
// The errors of one layer, as part of a style which has its source and sprites.
|
||||
function validateLayer(layer, source, spriteId) {
|
||||
return validateStyleMin({
|
||||
version: 8,
|
||||
sources: {[source]: {type: "vector", url: "pmtiles://overlay"}},
|
||||
|
|
@ -157,94 +19,16 @@ function validationErrors(layer, source, spriteId) {
|
|||
});
|
||||
}
|
||||
|
||||
// Turn a style written for another map into the layers which draw `file` on this one.
|
||||
// Returns {layers, skipped}: `skipped` counts the layers of this file which were not usable.
|
||||
const OPTIONS = {urls: MAP_URLS, validateLayer};
|
||||
|
||||
export function adaptOverlayStyle(style, file) {
|
||||
if (!style || !Array.isArray(style.layers)) return {layers: [], skipped: 0};
|
||||
|
||||
const fileLayerIds = new Set((file.vector_layers || []).map(l => l.id));
|
||||
const styleSource = chooseSource(style, fileLayerIds);
|
||||
const source = overlaySourceId(file);
|
||||
const spriteId = overlaySpriteId(file);
|
||||
// A style drawn for one scale (a printed map, say) is unreadable zoomed out; it can say the zoom
|
||||
// it is meant to be seen from.
|
||||
const minZoom = Number(style.metadata?.["wrolpi:minzoom"]);
|
||||
const layers = [];
|
||||
const ids = new Set();
|
||||
let skipped = 0;
|
||||
|
||||
for (const original of style.layers) {
|
||||
// Only layers which draw this file: not the background, nor another source (hillshade, contours).
|
||||
if (!original || original.source !== styleSource || !fileLayerIds.has(original["source-layer"])) continue;
|
||||
|
||||
const layer = JSON.parse(JSON.stringify(original));
|
||||
layer.id = `${source}:${layer["source-layer"]}:${original.id}`;
|
||||
layer.source = source;
|
||||
if (Number.isFinite(minZoom) && minZoom > (layer.minzoom || 0)) {
|
||||
layer.minzoom = minZoom;
|
||||
}
|
||||
|
||||
if (layer.layout?.["text-font"] !== undefined) {
|
||||
layer.layout["text-font"] = adaptFonts(layer.layout["text-font"]);
|
||||
}
|
||||
if (layer.layout?.["text-field"] !== undefined) {
|
||||
layer.layout["text-field"] = adaptTextFieldFonts(layer.layout["text-field"]);
|
||||
// MapLibre's own default font is not one the map has.
|
||||
if (layer.layout["text-font"] === undefined) {
|
||||
layer.layout["text-font"] = [FONT_REGULAR];
|
||||
}
|
||||
}
|
||||
for (const [group, properties] of Object.entries(IMAGE_PROPERTIES)) {
|
||||
for (const property of properties) {
|
||||
if (layer[group]?.[property] === undefined) continue;
|
||||
// Without a sprite sheet there are no images to draw. An image this cannot point at
|
||||
// the overlay's sprite would be looked for in the basemap's; the layer is drawn
|
||||
// without it (its text still is).
|
||||
const image = file.has_sprite ? adaptImage(layer[group][property], spriteId) : undefined;
|
||||
if (image === undefined) {
|
||||
delete layer[group][property];
|
||||
} else {
|
||||
layer[group][property] = image;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One bad layer must not stop the map: MapLibre refuses a whole style over it.
|
||||
let errors;
|
||||
try {
|
||||
errors = validationErrors(layer, source, spriteId);
|
||||
} catch (e) {
|
||||
errors = [e];
|
||||
}
|
||||
if (errors.length || ids.has(layer.id)) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
ids.add(layer.id);
|
||||
layers.push(layer);
|
||||
}
|
||||
return {layers, skipped};
|
||||
return shared.adaptOverlayStyle(style, file, OPTIONS);
|
||||
}
|
||||
|
||||
// Fetch and adapt the style beside an overlay file. Returns null when the file has none, or it
|
||||
// cannot be used; the overlay is then drawn generically.
|
||||
export async function loadOverlayStyle(file) {
|
||||
if (!file.style_path) return null;
|
||||
try {
|
||||
const response = await fetch(mediaUrl(file.style_path));
|
||||
if (!response.ok) return null;
|
||||
const adapted = adaptOverlayStyle(await response.json(), file);
|
||||
return adapted.layers.length ? adapted : null;
|
||||
} catch (e) {
|
||||
console.error(`Could not use the style of ${file.map_path}:`, e);
|
||||
return null;
|
||||
}
|
||||
export function loadOverlayStyle(file) {
|
||||
return shared.loadOverlayStyle(file, OPTIONS);
|
||||
}
|
||||
|
||||
// Attach its style to each overlay file which has one (`styleLayers`, `styleSkipped`).
|
||||
export async function loadOverlayStyles(overlays) {
|
||||
return Promise.all((overlays || []).map(async file => {
|
||||
const adapted = await loadOverlayStyle(file);
|
||||
return adapted ? {...file, styleLayers: adapted.layers, styleSkipped: adapted.skipped} : file;
|
||||
}));
|
||||
export function loadOverlayStyles(overlays) {
|
||||
return shared.loadOverlayStyles(overlays, OPTIONS);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,282 +1,29 @@
|
|||
// Which map files the viewer draws, and how it draws the ones that are not a Protomaps basemap.
|
||||
//
|
||||
// The API says what each PMTiles file is (`kind`): a `basemap` is drawn with the basemap theme,
|
||||
// `terrain` becomes hillshade and contours, and an `overlay` is any other vector or raster file.
|
||||
// An overlay has no style of its own, so its layers are drawn generically: one color per layer,
|
||||
// as fills, lines or circles.
|
||||
// The map viewer's side of the overlay code: the shared logic (../map-shared/overlays.js, which
|
||||
// the standalone viewer uses too) with the URLs of this app, where a map file is fetched from the
|
||||
// media directory.
|
||||
|
||||
import {escapeHtml} from "./mapPoiPopup";
|
||||
import * as shared from "../map-shared/overlays.js";
|
||||
|
||||
// Every MapLibre source and layer of an overlay starts with this, so the basemap's layer groups
|
||||
// (which match layer names like "water") never touch them.
|
||||
export const OVERLAY_PREFIX = "overlay:";
|
||||
export const STORAGE_KEY_OVERLAYS = "wrolpi-map-overlays";
|
||||
|
||||
const RASTER_SUFFIX = "raster";
|
||||
const VECTOR_TYPES = ["fill", "line", "circle"];
|
||||
// Readable on both the light and dark basemaps.
|
||||
const OVERLAY_COLORS = [
|
||||
"#e6194b", "#3cb44b", "#4363d8", "#f58231", "#b455e0", "#17a2a2",
|
||||
"#f032e6", "#b07a3b", "#d1495b", "#8a9a1b", "#5b7fff", "#e6a700",
|
||||
];
|
||||
const POPUP_MAX_FEATURES = 3;
|
||||
const POPUP_MAX_PROPERTIES = 12;
|
||||
|
||||
// Detect full planet files: "planet-20260329.pmtiles" or bare date like "20260329.pmtiles".
|
||||
export function isPlanetFile(name) {
|
||||
if (name.startsWith("planet-")) return true;
|
||||
return /^\d{8}\.pmtiles$/.test(name);
|
||||
}
|
||||
export * from "../map-shared/overlays.js";
|
||||
|
||||
// The URL path of a file in the media directory (`path` is relative to the media directory).
|
||||
export function mediaUrl(path) {
|
||||
return "/media/" + String(path).split("/").map(encodeURIComponent).join("/");
|
||||
return "/media/" + shared.encodePath(path);
|
||||
}
|
||||
|
||||
export function pmtilesUrl(path) {
|
||||
return `pmtiles://${mediaUrl(path)}`;
|
||||
}
|
||||
|
||||
// Sort the map files into what the viewer does with each. Ignored files (`visible: false`) and
|
||||
// unreadable files are left out. A planet file covers everything, so it replaces the regional
|
||||
// extracts; overlays and terrain are drawn either way.
|
||||
export function planMapFiles(files) {
|
||||
const visible = (files || []).filter(f => f.visible !== false);
|
||||
const basemaps = visible.filter(f => f.kind === "basemap");
|
||||
let planet = null;
|
||||
for (const f of basemaps) {
|
||||
if (isPlanetFile(f.name) && (!planet || f.size > planet.size)) planet = f;
|
||||
}
|
||||
const terrains = visible.filter(f => f.kind === "terrain");
|
||||
return {
|
||||
planet,
|
||||
regions: planet ? [] : basemaps,
|
||||
terrain: terrains.length ? terrains[terrains.length - 1] : null,
|
||||
overlays: visible.filter(f => f.kind === "overlay"),
|
||||
};
|
||||
}
|
||||
|
||||
export function isRasterOverlay(file) {
|
||||
return file.tile_type !== "mvt";
|
||||
}
|
||||
|
||||
// Whether the overlay is drawn with a style which came beside the file (see mapOverlayStyle.js).
|
||||
export function isStyledOverlay(file) {
|
||||
return !isRasterOverlay(file) && Array.isArray(file.styleLayers) && file.styleLayers.length > 0;
|
||||
}
|
||||
|
||||
// The layers of a vector overlay the user can show and hide: all of them, or with its own style
|
||||
// only those the style draws.
|
||||
export function overlayToggleLayers(file) {
|
||||
if (isRasterOverlay(file)) return [];
|
||||
const layers = file.vector_layers || [];
|
||||
if (!isStyledOverlay(file)) return layers;
|
||||
const drawn = new Set(file.styleLayers.map(l => l["source-layer"]));
|
||||
return layers.filter(l => drawn.has(l.id));
|
||||
}
|
||||
|
||||
function fileStem(name) {
|
||||
return String(name).replace(/\.pmtiles$/, "");
|
||||
}
|
||||
|
||||
// What to call an overlay: the name the file gives itself, else its file name. Files which would
|
||||
// share a label also show where they are.
|
||||
export function overlayLabel(file, files = []) {
|
||||
const base = f => (f.title && f.title.trim()) || fileStem(f.name);
|
||||
const label = base(file);
|
||||
const shared = files.some(f => f.map_path !== file.map_path && base(f) === label);
|
||||
return shared ? `${label} (${file.map_path})` : label;
|
||||
}
|
||||
|
||||
// A stable color for a layer: the same layer name is the same color in every file and session.
|
||||
export function overlayColor(layerId) {
|
||||
let hash = 5381;
|
||||
for (const c of String(layerId)) hash = ((hash * 33) ^ c.charCodeAt(0)) >>> 0;
|
||||
return OVERLAY_COLORS[hash % OVERLAY_COLORS.length];
|
||||
}
|
||||
|
||||
// --- What the user chose to see. {[map_path]: {enabled: bool, layers: {[layerId]: bool}}} ---
|
||||
|
||||
export function loadOverlayState() {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY_OVERLAYS));
|
||||
if (saved && typeof saved === "object" && !Array.isArray(saved)) return saved;
|
||||
} catch (e) { /* ignore */ }
|
||||
return {};
|
||||
}
|
||||
|
||||
export function saveOverlayState(state) {
|
||||
try { localStorage.setItem(STORAGE_KEY_OVERLAYS, JSON.stringify(state)); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
// An overlay is hidden until the user turns it on.
|
||||
export function isOverlayEnabled(state, file) {
|
||||
return state?.[file.map_path]?.enabled === true;
|
||||
}
|
||||
|
||||
// Once a file is on, each of its layers is drawn until the user turns that layer off.
|
||||
export function isOverlayLayerEnabled(state, file, layerId) {
|
||||
return state?.[file.map_path]?.layers?.[layerId] !== false;
|
||||
}
|
||||
|
||||
export function setOverlayEnabled(state, file, enabled) {
|
||||
return {...state, [file.map_path]: {...state?.[file.map_path], enabled}};
|
||||
}
|
||||
|
||||
export function setOverlayLayerEnabled(state, file, layerId, enabled) {
|
||||
const entry = state?.[file.map_path] || {};
|
||||
return {...state, [file.map_path]: {...entry, layers: {...entry.layers, [layerId]: enabled}}};
|
||||
}
|
||||
|
||||
export function setAllOverlayLayersEnabled(state, file, enabled) {
|
||||
const layers = {};
|
||||
for (const l of overlayToggleLayers(file)) layers[l.id] = enabled;
|
||||
return {...state, [file.map_path]: {...state?.[file.map_path], layers}};
|
||||
}
|
||||
|
||||
// --- MapLibre style ---
|
||||
|
||||
export function overlaySourceId(file) {
|
||||
return `${OVERLAY_PREFIX}${file.map_path}`;
|
||||
}
|
||||
|
||||
export function isOverlayLayerId(layerId) {
|
||||
return String(layerId).startsWith(OVERLAY_PREFIX);
|
||||
}
|
||||
|
||||
// MapLibre puts a source's attribution in the page as HTML, and this text comes from a file
|
||||
// someone downloaded: only its text is kept.
|
||||
function attributionText(attribution) {
|
||||
if (!attribution) return undefined;
|
||||
const text = new DOMParser().parseFromString(String(attribution), "text/html").body.textContent || "";
|
||||
return text.trim() ? escapeHtml(text.trim()) : undefined;
|
||||
}
|
||||
export const MAP_URLS = {
|
||||
pmtiles: file => pmtilesUrl(file.path),
|
||||
style: file => mediaUrl(file.style_path),
|
||||
};
|
||||
|
||||
export function buildOverlaySource(file) {
|
||||
const source = {type: isRasterOverlay(file) ? "raster" : "vector", url: pmtilesUrl(file.path)};
|
||||
if (isRasterOverlay(file)) source.tileSize = 256;
|
||||
const attribution = attributionText(file.attribution);
|
||||
if (attribution) source.attribution = attribution;
|
||||
return source;
|
||||
return shared.buildOverlaySource(file, MAP_URLS);
|
||||
}
|
||||
|
||||
// The geometry a generator recorded for a layer ("Point", "LineString", "Polygon") names the one
|
||||
// way to draw it. Without that, the layer is drawn all three ways, each limited to its geometry.
|
||||
const TYPE_OF_GEOMETRY = {Polygon: "fill", LineString: "line", Point: "circle"};
|
||||
const GEOMETRY_OF_TYPE = {fill: "Polygon", line: "LineString", circle: "Point"};
|
||||
|
||||
function paintOf(type, color) {
|
||||
if (type === "fill") return {"fill-color": color, "fill-opacity": 0.25, "fill-outline-color": color};
|
||||
if (type === "line") return {"line-color": color, "line-width": 1.5};
|
||||
return {
|
||||
"circle-color": color, "circle-radius": 4,
|
||||
"circle-stroke-color": "#ffffff", "circle-stroke-width": 1,
|
||||
};
|
||||
}
|
||||
|
||||
// The style layers of an overlay file, each already visible or hidden as `state` says; a source
|
||||
// with no visible layer requests no tiles.
|
||||
export function buildOverlayLayers(file, state) {
|
||||
const source = overlaySourceId(file);
|
||||
const enabled = isOverlayEnabled(state, file);
|
||||
const visibility = on => (on ? "visible" : "none");
|
||||
|
||||
if (isRasterOverlay(file)) {
|
||||
return [{
|
||||
id: `${source}:${RASTER_SUFFIX}`, type: "raster", source,
|
||||
layout: {visibility: visibility(enabled)},
|
||||
}];
|
||||
}
|
||||
|
||||
if (isStyledOverlay(file)) {
|
||||
// The file came with its own style: its layers, each shown when the file and its source
|
||||
// layer are on (and the style does not itself hide it).
|
||||
return file.styleLayers.map(layer => ({
|
||||
...layer,
|
||||
layout: {
|
||||
...layer.layout,
|
||||
visibility: visibility(enabled && layer.layout?.visibility !== "none"
|
||||
&& isOverlayLayerEnabled(state, file, layer["source-layer"])),
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
const styleLayers = [];
|
||||
for (const layer of file.vector_layers || []) {
|
||||
const color = overlayColor(layer.id);
|
||||
const known = TYPE_OF_GEOMETRY[layer.geometry];
|
||||
for (const type of known ? [known] : VECTOR_TYPES) {
|
||||
const styleLayer = {
|
||||
id: `${source}:${layer.id}:${type}`,
|
||||
type,
|
||||
source,
|
||||
"source-layer": layer.id,
|
||||
layout: {visibility: visibility(enabled && isOverlayLayerEnabled(state, file, layer.id))},
|
||||
paint: paintOf(type, color),
|
||||
};
|
||||
if (!known) styleLayer.filter = ["==", "$type", GEOMETRY_OF_TYPE[type]];
|
||||
styleLayers.push(styleLayer);
|
||||
}
|
||||
}
|
||||
return styleLayers;
|
||||
}
|
||||
|
||||
// Add the overlays to a style's sources and layers (the basemap's are already there). A raster
|
||||
// overlay goes under the basemap's labels so the map stays readable; vector overlays go on top:
|
||||
// an overlay with its own style in that style's order, then the generic ones, fills under lines
|
||||
// under points.
|
||||
export function addOverlaysToStyle(styleSources, allLayers, overlays, state) {
|
||||
const rasters = [];
|
||||
const styled = [];
|
||||
const vectors = {fill: [], line: [], circle: []};
|
||||
for (const file of overlays || []) {
|
||||
styleSources[overlaySourceId(file)] = buildOverlaySource(file);
|
||||
const layers = buildOverlayLayers(file, state);
|
||||
if (isStyledOverlay(file)) {
|
||||
styled.push(...layers);
|
||||
continue;
|
||||
}
|
||||
for (const layer of layers) {
|
||||
if (layer.type === "raster") rasters.push(layer);
|
||||
else vectors[layer.type].push(layer);
|
||||
}
|
||||
}
|
||||
const firstLabel = allLayers.findIndex(l => l.type === "symbol");
|
||||
allLayers.splice(firstLabel === -1 ? allLayers.length : firstLabel, 0, ...rasters);
|
||||
allLayers.push(...styled, ...vectors.fill, ...vectors.line, ...vectors.circle);
|
||||
}
|
||||
|
||||
// --- Popup ---
|
||||
|
||||
// The popup HTML of the overlay features under a click, or null when there are none. An overlay's
|
||||
// attributes are whatever its author chose, so they are listed as they are.
|
||||
export function overlayPopupHtml(features) {
|
||||
const seen = new Set();
|
||||
const blocks = [];
|
||||
for (const feature of features || []) {
|
||||
const layerId = feature.sourceLayer || feature.layer?.["source-layer"];
|
||||
const properties = feature.properties || {};
|
||||
if (!layerId) continue;
|
||||
const key = JSON.stringify([layerId, properties]);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
if (blocks.length >= POPUP_MAX_FEATURES) break;
|
||||
|
||||
const entries = Object.entries(properties).filter(([, v]) => v !== null && v !== undefined && v !== "");
|
||||
const name = properties.name;
|
||||
const rows = entries
|
||||
.filter(([k]) => k !== "name")
|
||||
.slice(0, POPUP_MAX_PROPERTIES)
|
||||
.map(([k, v]) => `<br/><small>${escapeHtml(k)}: ${escapeHtml(v)}</small>`);
|
||||
const more = entries.length - (name !== undefined ? 1 : 0) - rows.length;
|
||||
blocks.push(
|
||||
`<div style="font-size:13px">` +
|
||||
`<strong>${escapeHtml(name !== undefined && name !== "" ? name : layerId)}</strong>` +
|
||||
(name !== undefined && name !== "" ? `<br/><small>${escapeHtml(layerId)}</small>` : "") +
|
||||
rows.join("") +
|
||||
(more > 0 ? `<br/><small>… ${more} more</small>` : "") +
|
||||
`</div>`
|
||||
);
|
||||
}
|
||||
return blocks.length ? blocks.join('<hr style="margin:4px 0"/>') : null;
|
||||
return shared.addOverlaysToStyle(styleSources, allLayers, overlays, state, MAP_URLS);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import {addOverlaysToMap, orderOverlayLayers} from '../map-shared/overlays.js';
|
||||
import {
|
||||
addOverlaysToStyle,
|
||||
buildOverlayLayers,
|
||||
|
|
@ -283,3 +284,121 @@ describe('overlayPopupHtml', () => {
|
|||
expect(long).toContain('8 more');
|
||||
});
|
||||
});
|
||||
|
||||
describe('adding overlays to a map a layer at a time', () => {
|
||||
// A viewer which cannot check a layer first gives each to MapLibre by itself; MapLibre refuses
|
||||
// only the layers it cannot draw.
|
||||
const URLS = {pmtiles: f => `pmtiles:///data/${f.map_path}`, style: f => `/data/${f.style_map_path}`};
|
||||
|
||||
class FakeMap {
|
||||
constructor(layers = [], refuse = () => false) {
|
||||
this.layers = layers.map(l => ({...l}));
|
||||
this.sources = {};
|
||||
this.refuse = refuse;
|
||||
}
|
||||
|
||||
getStyle() {
|
||||
return {layers: this.layers};
|
||||
}
|
||||
|
||||
getSource(id) {
|
||||
return this.sources[id];
|
||||
}
|
||||
|
||||
addSource(id, source) {
|
||||
this.sources[id] = source;
|
||||
}
|
||||
|
||||
getLayer(id) {
|
||||
return this.layers.find(l => l.id === id);
|
||||
}
|
||||
|
||||
addLayer(layer, before) {
|
||||
// As MapLibre: a layer it cannot draw is reported and not added.
|
||||
if (this.refuse(layer)) return;
|
||||
const index = before ? this.layers.findIndex(l => l.id === before) : -1;
|
||||
this.layers.splice(index === -1 ? this.layers.length : index, 0, layer);
|
||||
}
|
||||
}
|
||||
|
||||
const BASEMAP = [{id: 'earth', type: 'fill'}, {id: 'places', type: 'symbol'}, {id: 'pois', type: 'symbol'}];
|
||||
|
||||
test('sources come from where this viewer is served them', () => {
|
||||
const map = new FakeMap(BASEMAP);
|
||||
addOverlaysToMap(map, [FEATURES, SATELLITE], {}, URLS);
|
||||
expect(map.sources).toEqual({
|
||||
'overlay:extras/features.pmtiles': {type: 'vector', url: 'pmtiles:///data/extras/features.pmtiles'},
|
||||
'overlay:satellite.pmtiles': {type: 'raster', url: 'pmtiles:///data/satellite.pmtiles', tileSize: 256},
|
||||
});
|
||||
});
|
||||
|
||||
test('layers are in the order a whole style would have them', () => {
|
||||
const map = new FakeMap(BASEMAP);
|
||||
const refused = addOverlaysToMap(map, [FEATURES, SATELLITE], {}, URLS);
|
||||
expect(refused).toEqual({});
|
||||
|
||||
const sources = {};
|
||||
const whole = BASEMAP.map(l => ({...l}));
|
||||
addOverlaysToStyle(sources, whole, [FEATURES, SATELLITE], {});
|
||||
expect(map.layers.map(l => l.id)).toEqual(whole.map(l => l.id));
|
||||
// The raster is under the basemap's labels.
|
||||
expect(map.layers.map(l => l.id).indexOf('overlay:satellite.pmtiles:raster')).toBe(1);
|
||||
});
|
||||
|
||||
test('layers are added as the user last chose to see them', () => {
|
||||
const map = new FakeMap(BASEMAP);
|
||||
const state = setOverlayLayerEnabled(setOverlayEnabled({}, FEATURES, true), FEATURES, 'towers', false);
|
||||
addOverlaysToMap(map, [FEATURES], state, URLS);
|
||||
const visibility = id => map.getLayer(`overlay:extras/features.pmtiles:${id}`).layout.visibility;
|
||||
expect([visibility('power_lines:line'), visibility('towers:circle')]).toEqual(['visible', 'none']);
|
||||
});
|
||||
|
||||
test('a layer MapLibre refuses is counted against its file, and the rest are added', () => {
|
||||
const map = new FakeMap(BASEMAP, layer => layer.id.includes(':towers:'));
|
||||
const other = file('other.pmtiles', {vector_layers: [layer('towers', 'Point'), layer('roads', 'LineString')]});
|
||||
const refused = addOverlaysToMap(map, [FEATURES, other], {}, URLS);
|
||||
expect(refused).toEqual({'extras/features.pmtiles': 1, 'other.pmtiles': 1});
|
||||
expect(map.layers.map(l => l.id)).toEqual([
|
||||
'earth', 'places', 'pois',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'overlay:other.pmtiles:roads:line',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a layer which throws is refused too', () => {
|
||||
const map = new FakeMap(BASEMAP, (layer) => {
|
||||
if (layer.type === 'line') throw new Error('bad layer');
|
||||
return false;
|
||||
});
|
||||
expect(addOverlaysToMap(map, [FEATURES], {}, URLS)).toEqual({'extras/features.pmtiles': 1});
|
||||
});
|
||||
|
||||
test('adding again changes nothing: the style keeps one of each', () => {
|
||||
const map = new FakeMap(BASEMAP);
|
||||
addOverlaysToMap(map, [FEATURES], {}, URLS);
|
||||
const before = map.layers.map(l => l.id);
|
||||
expect(addOverlaysToMap(map, [FEATURES], {}, URLS)).toEqual({});
|
||||
expect(map.layers.map(l => l.id)).toEqual(before);
|
||||
});
|
||||
|
||||
test('an overlay with its own style keeps that style\'s order, under the generic ones', () => {
|
||||
const styled = {
|
||||
...FEATURES,
|
||||
map_path: 'styled.pmtiles',
|
||||
styleLayers: [
|
||||
{id: 'overlay:styled.pmtiles:towers:icons', type: 'symbol', source: 'overlay:styled.pmtiles', 'source-layer': 'towers'},
|
||||
{id: 'overlay:styled.pmtiles:flood_zones:area', type: 'fill', source: 'overlay:styled.pmtiles', 'source-layer': 'flood_zones'},
|
||||
],
|
||||
};
|
||||
const {rasters, vectors} = orderOverlayLayers([FEATURES, styled, SATELLITE], {});
|
||||
expect(rasters.map(l => l.id)).toEqual(['overlay:satellite.pmtiles:raster']);
|
||||
expect(vectors.map(l => l.id)).toEqual([
|
||||
'overlay:styled.pmtiles:towers:icons',
|
||||
'overlay:styled.pmtiles:flood_zones:area',
|
||||
'overlay:extras/features.pmtiles:flood_zones:fill',
|
||||
'overlay:extras/features.pmtiles:power_lines:line',
|
||||
'overlay:extras/features.pmtiles:towers:circle',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -2,14 +2,7 @@
|
|||
// The Protomaps basemap keeps name, kind, kind_detail and elevation; there is no address,
|
||||
// phone or opening hours to show.
|
||||
|
||||
export function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
import {escapeHtml} from "../map-shared/overlays.js";
|
||||
|
||||
// "american_football" -> "American football"
|
||||
function humanize(value) {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue