// Which map files a viewer draws, and how it draws the ones that are not a Protomaps basemap. // // SHARED by the map viewer of the app and the standalone viewer (modules/map/static/index.html), // which loads the copy in modules/map/static/js/. It must stay a plain ES module a browser can // load as it is: no imports from packages, and relative imports with their `.js`. After changing // it, run `npm run sync:map-shared`; a test fails while the copy differs. // // What differs between the viewers is passed in as `urls`: `{pmtiles(file), style(file)}`, the // URL of an overlay's PMTiles file (`pmtiles://...`) and of the style beside it. // // 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. export function escapeHtml(value) { return String(value) .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } // 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); } // A path as part of a URL: each of its parts is encoded (a `#` or `?` in a file name would // otherwise end the path). export function encodePath(path) { return String(path).split("/").map(encodeURIComponent).join("/"); } // 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; } // The layers of the schemas a basemap is commonly made in (Protomaps, which the map's own basemap // is, and OpenMapTiles). A file which also has other things often carries these too, and drawing // them again over the basemap doubles every road and label. const BASEMAP_LAYERS = new Set([ // Protomaps "earth", "water", "roads", "landuse", "landcover", "buildings", "boundaries", "places", "pois", "transit", "natural", "physical_line", "physical_point", // OpenMapTiles "waterway", "water_name", "landuse", "landcover", "park", "boundary", "aeroway", "aerodrome_label", "transportation", "transportation_name", "building", "place", "poi", "mountain_peak", ]); // Whether a layer of an overlay is of something the basemap already draws. export function isBasemapLayer(layerId) { return BASEMAP_LAYERS.has(String(layerId ?? "").toLowerCase()); } // Once a file is on, each of its layers is as the user chose. A layer the user has not chosen for // is drawn, unless the basemap already draws the same thing. export function isOverlayLayerEnabled(state, file, layerId) { const chosen = state?.[file.map_path]?.layers?.[layerId]; return typeof chosen === "boolean" ? chosen : !isBasemapLayer(layerId); } 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 function buildOverlaySource(file, urls) { const source = {type: isRasterOverlay(file) ? "raster" : "vector", url: urls.pmtiles(file)}; if (isRasterOverlay(file)) source.tileSize = 256; const attribution = attributionText(file.attribution); if (attribution) source.attribution = attribution; return source; } // 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; } // Whether a layer of an overlay is of its labels: its text, its icons, and the points it marks. The // rest of an overlay is its ground: areas, lines, pictures. export function isOverlayLabelLayer(layer) { return layer?.type === "symbol" || layer?.type === "circle"; } // The style layers of every overlay, in the order they are drawn. Labels are always on top: the // ground of every overlay goes under the basemap's labels (`under`), so an area an overlay fills // does not cover the name of what is in it, and the labels of every overlay go over them (`over`). // In each, a raster is lowest, then an overlay with its own style in that style's order, then the // generic ones, fills under lines under points. export function orderOverlayLayers(overlays, state) { const rasters = []; const styled = []; const generic = {fill: [], line: [], circle: []}; for (const file of overlays || []) { 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 generic[layer.type].push(layer); } } const vectors = [...styled, ...generic.fill, ...generic.line, ...generic.circle]; return { under: [...rasters, ...vectors.filter(layer => !isOverlayLabelLayer(layer))], over: vectors.filter(isOverlayLabelLayer), }; } // The layers of a basemap with every label over all of its ground: the ground in the order it was // in, then the labels in the order they were in. // // A map of several basemap files is their layers one file after another, so the labels of each file // but the last are under the land, the water and the roads of the files after it, and under // anything which is put under "the labels". Labels are always on top. export function labelsOverGround(layers) { layers = layers || []; return [...layers.filter(l => l.type !== "symbol"), ...layers.filter(l => l.type === "symbol")]; } // The source of the contour lines both viewers draw from the terrain. They are added to a style // after the basemap's labels, lines and labels both, and are not of the basemap. const CONTOUR_SOURCE = "contours"; // Where the basemap's labels begin: the index of the first of the labels which are over all of the // basemap's ground. Where no label is over its ground, the index after the last of its ground. // // Not the map's first label: a map of several basemap files has the labels of the first file under // the ground of the next, and an overlay put there would be under the land and the water of every // file after the first. Nor before the last layer which is not a label: the contour lines are // drawn after the basemap's labels, and an overlay put under them would be over every label. export function basemapLabelsStart(layers) { layers = layers || []; const ofBasemap = layer => !isOverlayLayerId(layer.id) && layer.source !== CONTOUR_SOURCE; let lastGround = -1; for (let i = layers.length - 1; i >= 0; i--) { if (ofBasemap(layers[i]) && layers[i].type !== "symbol") { lastGround = i; break; } } for (let i = lastGround + 1; i < layers.length; i++) { if (ofBasemap(layers[i]) && layers[i].type === "symbol") return i; } return lastGround + 1; } // Add the overlays to a style's sources and layers (the basemap's are already there). export function addOverlaysToStyle(styleSources, allLayers, overlays, state, urls) { for (const file of overlays || []) { styleSources[overlaySourceId(file)] = buildOverlaySource(file, urls); } const {under, over} = orderOverlayLayers(overlays, state); allLayers.splice(basemapLabelsStart(allLayers), 0, ...under); allLayers.push(...over); } // Add the overlays to a map whose style has loaded, a layer at a time. For a viewer which cannot // check a layer before giving it to MapLibre: MapLibre refuses a whole style over one layer it // cannot draw, but refuses only that layer when it is added by itself. // Returns how many layers of each file (by `map_path`) were refused. export function addOverlaysToMap(map, overlays, state, urls) { const refused = {}; for (const file of overlays || []) { const id = overlaySourceId(file); if (!map.getSource(id)) map.addSource(id, buildOverlaySource(file, urls)); } const mapLayers = map.getStyle()?.layers || []; const firstLabel = mapLayers[basemapLabelsStart(mapLayers)]; const {under, over} = orderOverlayLayers(overlays, state); const add = (layer, before) => { if (map.getLayer(layer.id)) return; try { map.addLayer(layer, before); } catch (e) { /* refused; counted below */ } if (!map.getLayer(layer.id)) { const mapPath = (overlays || []).find(f => layer.source === overlaySourceId(f))?.map_path; refused[mapPath] = (refused[mapPath] || 0) + 1; } }; for (const layer of under) add(layer, firstLabel?.id); for (const layer of over) add(layer, undefined); return refused; } // --- 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]) => `
${escapeHtml(k)}: ${escapeHtml(v)}`); const more = entries.length - (name !== undefined ? 1 : 0) - rows.length; blocks.push( `
` + `${escapeHtml(name !== undefined && name !== "" ? name : layerId)}` + (name !== undefined && name !== "" ? `
${escapeHtml(layerId)}` : "") + rows.join("") + (more > 0 ? `
… ${more} more` : "") + `
` ); } return blocks.length ? blocks.join('
') : null; }