This commit is contained in:
vcoppe committed 2026-11-29 12:52:41 +01:00
1 parent 1bd8ac46fe
commit 2cf9a9f982
6 files changed
+545 -12

No files matched your search

+2
View File
@@ -10,6 +10,7 @@ import { settings } from '$lib/state/settings';
import { tick } from 'svelte';
import { ANCHOR_LAYER_KEY, StyleManager } from '$lib/components/map/style';
import { MapLayerEventManager } from '$lib/components/map/map-layer-event-manager';
import { registerOpenSatelliteProtocol } from '$lib/components/map/open-satellite';
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
@@ -41,6 +42,7 @@ export class MapLibreGLMap {
geolocate: boolean
) {
maplibregl.setWorkerUrl(workerUrl);
registerOpenSatelliteProtocol(maptilerKey);
this._maptilerKey = maptilerKey;
this._styleManager = new StyleManager(this._mapStore, this._maptilerKey);
// MapLibre gives Safari more workers, but only recognizes it by its user agent: not
@@ -0,0 +1,57 @@
// Which imagery each tile of the open satellite basemap is made of.
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import { planTile } from './open-satellite';
function tile(lon: number, lat: number, z: number): [number, number, number] {
const n = 2 ** z;
const sin = Math.sin((lat * Math.PI) / 180);
return [
z,
Math.floor(((lon + 180) / 360) * n),
Math.floor((0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI)) * n),
];
}
async function plan(lon: number, lat: number, z: number) {
const { parts, fallback } = await planTile(...tile(lon, lat, z));
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`), fallback };
}
describe('planTile', () => {
it('takes a tile inside a country from its agency alone', async () => {
assert.deepEqual(await plan(2.35, 48.85, 15), { parts: ['fr:full'], fallback: false });
assert.deepEqual(await plan(6.63, 46.52, 15), { parts: ['ch:full'], fallback: false });
assert.deepEqual(await plan(4.35, 50.85, 16), { parts: ['be:full'], fallback: false });
assert.deepEqual(await plan(21.01, 52.23, 16), { parts: ['pl:full'], fallback: false });
});
it('takes a tile outside every country from the fallback', async () => {
assert.deepEqual(await plan(-0.12, 51.5, 14), { parts: [], fallback: true });
// Germany, which is not in the patchwork
assert.deepEqual(await plan(9.73, 52.37, 14), { parts: [], fallback: true });
assert.deepEqual(await plan(-30, 40, 10), { parts: [], fallback: true });
});
it('puts the countries of a border tile together, over the fallback where none is', async () => {
// Menton: France and Italy, which is not in the patchwork
assert.deepEqual(await plan(7.5, 43.8, 12), {
parts: ['fr:partial'],
fallback: true,
});
// Basel: Switzerland, France and Germany
assert.deepEqual(await plan(7.589, 47.5895, 14), {
parts: ['ch:partial', 'fr:partial'],
fallback: true,
});
// Somport: France and Spain, between them the whole tile
assert.deepEqual(await plan(-0.52, 42.8, 13), {
parts: ['fr:partial', 'es:partial'],
fallback: false,
});
});
it('does not take a tile covering several countries from their agencies', async () => {
assert.deepEqual(await plan(2.35, 48.85, 6), { parts: [], fallback: true });
});
});
@@ -0,0 +1,444 @@
import * as maplibregl from 'maplibre-gl';
/**
* A satellite basemap made of the open imagery of national mapping agencies, drawn through a
* custom protocol: each tile is taken from the agency whose country covers it, the tiles on a
* border are put together on a canvas clipped to the border of each country, and only the parts
* no open source covers are taken from the commercial fallback.
*/
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
type TileUrl = (z: number, x: number, y: number) => string;
type ImagerySource = {
/** Key of the coverage in satellite-coverage.json */
id: string;
url: TileUrl;
/** Below it, a tile spans too many sources and the fallback is used. */
minzoom: number;
/** Above it, the tile of this zoom level is scaled up. */
maxzoom: number;
};
const xyz =
(template: string): TileUrl =>
(z, x, y) =>
template.replace('{z}', String(z)).replace('{x}', String(x)).replace('{y}', String(y));
/** In order of priority, the first one covering a point is used. */
const sources: ImagerySource[] = [
{
id: 'ch',
url: xyz(
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
),
minzoom: 8,
maxzoom: 20,
},
{
id: 'fr',
url: xyz(
'https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&FORMAT=image/jpeg&TILEMATRIXSET=PM&TILEMATRIX={z}&TILECOL={x}&TILEROW={y}'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'es',
url: xyz(
'https://www.ign.es/wmts/pnoa-ma?layer=OI.OrthoimageCoverage&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'at',
url: xyz(
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'nl',
url: xyz(
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'lu',
url: xyz(
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'cz',
url: xyz(
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'be',
url: xyz(
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
),
minzoom: 8,
maxzoom: 19,
},
{
id: 'pl',
url: xyz(
'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}'
),
minzoom: 8,
maxzoom: 19,
},
];
export const openSatelliteAttribution = [
'<a href="https://www.swisstopo.admin.ch/" target="_blank">swisstopo</a>',
'<a href="https://geoservices.ign.fr/" target="_blank">IGN-F/Géoplateforme</a>',
'PNOA © <a href="https://www.ign.es/" target="_blank">IGN España</a>',
'<a href="https://basemap.at/" target="_blank">basemap.at</a>',
'<a href="https://www.pdok.nl/" target="_blank">PDOK</a>',
'<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
'<a href="https://cuzk.gov.cz/" target="_blank">ČÚZK</a>',
'<a href="https://www.ngi.be/" target="_blank">NGI/IGN</a>',
'<a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>',
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>',
].join(', ');
// Geometry, in Web Mercator coordinates between 0 and 1
type Ring = Float64Array; // x0, y0, x1, y1, ...
type Polygon = { rings: Ring[]; bbox: [number, number, number, number] };
type Coverage = { polygons: Polygon[]; bbox: [number, number, number, number] };
type Rect = [number, number, number, number]; // minX, minY, maxX, maxY
function mercatorX(lon: number) {
return (lon + 180) / 360;
}
function mercatorY(lat: number) {
const sin = Math.sin((Math.max(-85.0511, Math.min(85.0511, lat)) * Math.PI) / 180);
return 0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI);
}
function emptyBBox(): [number, number, number, number] {
return [Infinity, Infinity, -Infinity, -Infinity];
}
function extend(bbox: [number, number, number, number], other: Rect) {
bbox[0] = Math.min(bbox[0], other[0]);
bbox[1] = Math.min(bbox[1], other[1]);
bbox[2] = Math.max(bbox[2], other[2]);
bbox[3] = Math.max(bbox[3], other[3]);
}
function intersects(a: Rect, b: Rect) {
return a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
}
function projectCoverage(polygons: number[][][][]): Coverage {
const coverage: Coverage = { polygons: [], bbox: emptyBBox() };
for (const polygon of polygons) {
const projected: Polygon = { rings: [], bbox: emptyBBox() };
for (const ring of polygon) {
const array = new Float64Array(ring.length * 2);
ring.forEach(([lon, lat], i) => {
array[2 * i] = mercatorX(lon);
array[2 * i + 1] = mercatorY(lat);
extend(projected.bbox, [
array[2 * i],
array[2 * i + 1],
array[2 * i],
array[2 * i + 1],
]);
});
projected.rings.push(array);
}
coverage.polygons.push(projected);
extend(coverage.bbox, projected.bbox);
}
return coverage;
}
function pointInPolygon(x: number, y: number, polygon: Polygon) {
let inside = false;
for (const ring of polygon.rings) {
for (let i = 0, j = ring.length - 2; i < ring.length; j = i, i += 2) {
const xi = ring[i],
yi = ring[i + 1],
xj = ring[j],
yj = ring[j + 1];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) {
inside = !inside;
}
}
}
return inside;
}
/** Whether the segment touches the rectangle (Liang–Barsky). */
function segmentIntersectsRect(
x0: number,
y0: number,
x1: number,
y1: number,
[minX, minY, maxX, maxY]: Rect
) {
let t0 = 0,
t1 = 1;
const dx = x1 - x0,
dy = y1 - y0;
const p = [-dx, dx, -dy, dy];
const q = [x0 - minX, maxX - x0, y0 - minY, maxY - y0];
for (let i = 0; i < 4; i++) {
if (p[i] === 0) {
if (q[i] < 0) return false;
} else {
const t = q[i] / p[i];
if (p[i] < 0) {
if (t > t1) return false;
t0 = Math.max(t0, t);
} else {
if (t < t0) return false;
t1 = Math.min(t1, t);
}
}
}
return true;
}
type CoverageRelation = { relation: 'full' | 'partial' | 'none'; polygons: Polygon[] };
function relate(coverage: Coverage, rect: Rect): CoverageRelation {
if (!intersects(coverage.bbox, rect)) return { relation: 'none', polygons: [] };
const touching: Polygon[] = [];
let crossed = false;
for (const polygon of coverage.polygons) {
if (!intersects(polygon.bbox, rect)) continue;
let polygonCrossed = false;
for (const ring of polygon.rings) {
for (let i = 2; i < ring.length && !polygonCrossed; i += 2) {
if (segmentIntersectsRect(ring[i - 2], ring[i - 1], ring[i], ring[i + 1], rect)) {
polygonCrossed = true;
}
}
if (polygonCrossed) break;
}
if (polygonCrossed) {
crossed = true;
touching.push(polygon);
} else if (pointInPolygon((rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2, polygon)) {
// No border inside the tile, and its center is inside: the whole tile is
return { relation: 'full', polygons: [polygon] };
}
}
return crossed
? { relation: 'partial', polygons: touching }
: { relation: 'none', polygons: [] };
}
// Coverage, loaded with the first tile
let coverages: Promise<Map<string, Coverage>> | null = null;
function getCoverages() {
coverages ??= import('$lib/data/satellite-coverage.json').then((module) => {
const data = module.default as unknown as Record<string, number[][][][]>;
const result = new Map<string, Coverage>();
for (const source of sources) {
result.set(source.id, projectCoverage(data[source.id] ?? []));
}
return result;
});
return coverages;
}
// Tiles
const TILE_SIZE = 256;
async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer | null> {
try {
const response = await fetch(url, { signal });
if (!response.ok) return null;
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.startsWith('image/')) return null;
return await response.arrayBuffer();
} catch (e) {
if (signal.aborted) throw e;
return null;
}
}
/** The image of the tile, or of the part of its ancestor at the max zoom of the source. */
async function fetchImage(
url: TileUrl,
maxzoom: number,
z: number,
x: number,
y: number,
signal: AbortSignal
): Promise<{ image: ImageBitmap; sx: number; sy: number; size: number } | null> {
const d = Math.max(0, z - maxzoom);
const bytes = await fetchBytes(url(z - d, x >> d, y >> d), signal);
if (!bytes) return null;
try {
const image = await createImageBitmap(new Blob([bytes]));
const size = image.width / 2 ** d;
return {
image,
sx: (x - ((x >> d) << d)) * size,
sy: (y - ((y >> d) << d)) * size,
size,
};
} catch {
return null;
}
}
function clipTo(
context: OffscreenCanvasRenderingContext2D,
polygons: Polygon[],
z: number,
x: number,
y: number
) {
const scale = 2 ** z * TILE_SIZE;
context.beginPath();
for (const polygon of polygons) {
for (const ring of polygon.rings) {
for (let i = 0; i < ring.length; i += 2) {
const px = ring[i] * scale - x * TILE_SIZE;
const py = ring[i + 1] * scale - y * TILE_SIZE;
if (i === 0) context.moveTo(px, py);
else context.lineTo(px, py);
}
context.closePath();
}
}
context.clip('evenodd');
}
/** Whether every point of a grid over the tile is in one of the partial coverages. */
function coveredBy(partials: CoverageRelation[], rect: Rect) {
const steps = 6;
for (let i = 0; i < steps; i++) {
for (let j = 0; j < steps; j++) {
const px = rect[0] + ((i + 0.5) / steps) * (rect[2] - rect[0]);
const py = rect[1] + ((j + 0.5) / steps) * (rect[3] - rect[1]);
if (
!partials.some((p) => p.polygons.some((polygon) => pointInPolygon(px, py, polygon)))
) {
return false;
}
}
}
return true;
}
type TilePart = CoverageRelation & { source: ImagerySource };
/**
* The sources of the tile, in drawing order: the one covering the whole tile, or those
* covering part of it, and whether the fallback is needed below them.
*/
export async function planTile(
z: number,
x: number,
y: number
): Promise<{ parts: TilePart[]; fallback: boolean }> {
const n = 2 ** z;
const rect: Rect = [x / n, y / n, (x + 1) / n, (y + 1) / n];
const coverageBySource = await getCoverages();
const parts: TilePart[] = [];
for (const source of sources) {
if (z < source.minzoom) continue;
const relation = relate(coverageBySource.get(source.id)!, rect);
if (relation.relation === 'full') {
return { parts: [{ ...relation, source }], fallback: false };
} else if (relation.relation === 'partial') {
parts.push({ ...relation, source });
}
}
return { parts, fallback: parts.length === 0 || !coveredBy(parts, rect) };
}
export function maptilerSource(maptilerKey: string): ImagerySource {
return {
id: 'fallback',
url: xyz(`https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=${maptilerKey}`),
minzoom: 0,
maxzoom: 20,
};
}
export async function loadTile(
z: number,
x: number,
y: number,
fallback: ImagerySource,
signal: AbortSignal
): Promise<ArrayBuffer | ImageBitmap> {
const plan = await planTile(z, x, y);
const { parts } = plan;
// a single tile as it is, without drawing it again
const single =
parts.length === 0
? fallback
: parts.length === 1 && !plan.fallback && parts[0].relation === 'full'
? parts[0].source
: null;
if (single && z <= single.maxzoom) {
const bytes = await fetchBytes(single.url(z, x, y), signal);
if (bytes) return bytes;
if (single === fallback) throw new Error(`No imagery for tile ${z}/${x}/${y}`);
}
const images = await Promise.all(
parts.map((p) => fetchImage(p.source.url, p.source.maxzoom, z, x, y, signal))
);
const fallbackImage =
plan.fallback || images.some((image) => image === null)
? await fetchImage(fallback.url, fallback.maxzoom, z, x, y, signal)
: null;
const canvas = new OffscreenCanvas(TILE_SIZE, TILE_SIZE);
const context = canvas.getContext('2d')!;
if (fallbackImage) {
const { image, sx, sy, size } = fallbackImage;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
image.close();
}
parts.forEach((p, i) => {
const result = images[i];
if (!result) return;
context.save();
if (p.relation === 'partial') clipTo(context, p.polygons, z, x, y);
const { image, sx, sy, size } = result;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
context.restore();
image.close();
});
return canvas.transferToImageBitmap();
}
export function registerOpenSatelliteProtocol(maptilerKey: string) {
const fallback = maptilerSource(maptilerKey);
maplibregl.addProtocol(OPEN_SATELLITE_PROTOCOL, async (params, abortController) => {
const match = params.url.match(/(\d+)\/(\d+)\/(\d+)$/);
if (!match) throw new Error(`Invalid tile URL: ${params.url}`);
const [z, x, y] = match.slice(1).map(Number);
return { data: await loadTile(z, x, y, fallback, abortController.signal) };
});
}