diff --git a/website/src/lib/components/map/open-satellite.test.ts b/website/src/lib/components/map/open-satellite.test.ts
index dcdc065a3..f99d012d5 100644
--- a/website/src/lib/components/map/open-satellite.test.ts
+++ b/website/src/lib/components/map/open-satellite.test.ts
@@ -3,7 +3,7 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
-import { planTile, type CountryTiles } from './open-satellite';
+import { fallbackNeeded, planTile, type CountryTiles } from './open-satellite';
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
@@ -96,3 +96,31 @@ describe('planTile', () => {
assert.deepEqual(asked, [`12/${x}/${y}`]);
});
});
+
+describe('fallbackNeeded', () => {
+ it('is not needed up to zoom 12, where the imagery of the whole world is', async () => {
+ const { asked, tiles } = savedTiles();
+ // a tile of 512 pixels at zoom 11 covers four tiles of the open imagery at zoom 12
+ assert.equal(await fallbackNeeded(...tile(-0.12, 51.5, 11), tiles), false);
+ assert.deepEqual(asked, []);
+ });
+
+ it('is needed far from every country, without asking for countries', async () => {
+ const { asked, tiles } = savedTiles();
+ assert.equal(await fallbackNeeded(...tile(-0.12, 51.5, 13), tiles), true);
+ assert.deepEqual(asked, []);
+ });
+
+ it('is not needed where the countries cover its four tiles', async () => {
+ const { tiles } = savedTiles();
+ // Paris, and Wattrelos between France and Belgium
+ assert.equal(await fallbackNeeded(...tile(2.35, 48.85, 14), tiles), false);
+ assert.equal(await fallbackNeeded(12, 2083, 1375, tiles), false);
+ });
+
+ it('is needed where one of its four tiles is outside the countries', async () => {
+ const { tiles } = savedTiles();
+ // Basel, with a tile entirely in Germany
+ assert.equal(await fallbackNeeded(12, 2134, 1430, tiles), true);
+ });
+});
diff --git a/website/src/lib/components/map/open-satellite.ts b/website/src/lib/components/map/open-satellite.ts
index 8802ecb18..4e1a52a83 100644
--- a/website/src/lib/components/map/open-satellite.ts
+++ b/website/src/lib/components/map/open-satellite.ts
@@ -3,10 +3,13 @@ import { VectorTile } from '@mapbox/vector-tile';
import { PbfReader } from 'pbf';
/**
- * 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.
+ * A satellite basemap made of the open imagery of national mapping agencies, in two layers drawn
+ * through custom protocols:
+ * - above, the open imagery: 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
+ * the rest is transparent;
+ * - below, the commercial fallback, whose tiles are only fetched where the open imagery leaves
+ * something to see.
*/
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
@@ -111,7 +114,6 @@ export const openSatelliteAttribution = [
'ČÚZK',
'NGI/IGN',
'GUGiK',
- '© MapTiler',
].join(', ');
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
@@ -351,53 +353,39 @@ export async function planTile(
};
}
-export function maptilerSource(maptilerKey: string): ImagerySource {
- return {
- id: 'fallback',
- url: xyz(`https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=${maptilerKey}`),
- maxzoom: 18,
- };
+function transparentTile() {
+ const canvas = new OffscreenCanvas(1, 1);
+ // without a context, the canvas cannot give its image
+ canvas.getContext('2d');
+ return canvas.transferToImageBitmap();
}
+/**
+ * The tile of the layer of the open imagery: up to zoom 12, the imagery of the whole world, and
+ * above, the imagery of each country clipped to its border, transparent where there is none.
+ */
export async function loadTile(
z: number,
x: number,
y: number,
- commercialFallback: ImagerySource,
signal: AbortSignal
): Promise {
- const fallback = z <= world.maxzoom ? world : commercialFallback;
- const plan = await planTile(z, x, y);
- const { parts } = plan;
+ if (z <= world.maxzoom) {
+ return (await fetchBytes(world.url(z, x, y), signal)) ?? transparentTile();
+ }
+ const { parts } = await planTile(z, x, y);
+ if (parts.length === 0) return transparentTile();
// 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}`);
+ if (parts.length === 1 && parts[0].relation === 'full' && z <= parts[0].source.maxzoom) {
+ return (await fetchBytes(parts[0].source.url(z, x, y), signal)) ?? transparentTile();
}
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;
@@ -411,12 +399,58 @@ export async function loadTile(
return canvas.transferToImageBitmap();
}
+// The commercial fallback, in its own layer below, with its tiles of 512 pixels as they are
+
+export const OPEN_SATELLITE_FALLBACK_PROTOCOL = 'opensat-fallback';
+
+export const openSatelliteFallbackAttribution =
+ '© MapTiler';
+
+/**
+ * Whether the tile of 512 pixels of the fallback is seen somewhere: whether one of the four
+ * tiles of 256 pixels of the open imagery that it covers, one zoom level above, needs it.
+ */
+export async function fallbackNeeded(
+ z: number,
+ x: number,
+ y: number,
+ tiles: CountryTiles = fetchCountryTile
+): Promise {
+ const plans = await Promise.all(
+ [0, 1, 2, 3].map((i) => planTile(z + 1, 2 * x + (i % 2), 2 * y + (i >> 1), tiles))
+ );
+ return plans.some((plan) => plan.fallback && z + 1 > world.maxzoom);
+}
+
+export async function loadFallbackTile(
+ z: number,
+ x: number,
+ y: number,
+ maptilerKey: string,
+ signal: AbortSignal
+): Promise {
+ if (!(await fallbackNeeded(z, x, y))) return transparentTile();
+ const url = `https://api.maptiler.com/tiles/satellite-v2/${z}/${x}/${y}.jpg?key=${maptilerKey}`;
+ const response = await fetch(url, { signal });
+ if (!response.ok) throw new Error(`No imagery for tile ${z}/${x}/${y}: ${response.status}`);
+ return await response.arrayBuffer();
+}
+
+function tileOf(url: string) {
+ const match = url.match(/(\d+)\/(\d+)\/(\d+)$/);
+ if (!match) throw new Error(`Invalid tile URL: ${url}`);
+ return match.slice(1).map(Number) as [number, number, number];
+}
+
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) };
+ const [z, x, y] = tileOf(params.url);
+ return { data: await loadTile(z, x, y, abortController.signal) };
+ });
+ maplibregl.addProtocol(OPEN_SATELLITE_FALLBACK_PROTOCOL, async (params, abortController) => {
+ const [z, x, y] = tileOf(params.url);
+ return {
+ data: await loadFallbackTile(z, x, y, maptilerKey, abortController.signal),
+ };
});
}
diff --git a/website/src/lib/components/map/style.test.ts b/website/src/lib/components/map/style.test.ts
index 446d24762..f96c42954 100644
--- a/website/src/lib/components/map/style.test.ts
+++ b/website/src/lib/components/map/style.test.ts
@@ -3,10 +3,11 @@ import assert from 'node:assert/strict';
import { afterEach, beforeEach, describe, it } from 'node:test';
import type { Map as MapLibreMap, StyleSpecification } from 'maplibre-gl';
import { writable } from 'svelte/store';
-import { overlays, type LayerTreeType } from '$lib/data/layers';
+import { basemaps, overlays, type LayerTreeType } from '$lib/data/layers';
import { engine } from '$lib/engine';
import { settings } from '$lib/state/settings';
import { StyleManager } from './style';
+import { openSatelliteAttribution, openSatelliteFallbackAttribution } from './open-satellite';
const URL_A = 'https://example.com/a.json';
const URL_B = 'https://example.com/b.json';
@@ -218,3 +219,34 @@ describe('StyleManager, with the style URL of an extension', () => {
assert.ok(fake.layers.has('tiles'));
});
});
+
+describe('StyleManager, with a basemap of the open satellite imagery', () => {
+ it('gives its imagery the credits of the agencies, its fallback those of MapTiler, and leaves the other sources alone', async () => {
+ answerWith({
+ [basemaps.libertySatellite as string]: {
+ version: 8,
+ sources: {
+ satellite: { type: 'raster', tiles: ['opensat://{z}/{x}/{y}'], tileSize: 256 },
+ fallback: {
+ type: 'raster',
+ tiles: ['opensat-fallback://{z}/{x}/{y}'],
+ tileSize: 512,
+ },
+ other: { type: 'raster', tiles: ['https://other/{z}/{x}/{y}'] },
+ },
+ layers: [{ id: 'satellite', type: 'raster', source: 'satellite' }],
+ },
+ });
+ const manager = new StyleManager(writable(null), 'key');
+ const built = await manager.buildStyle('libertySatellite');
+ assert.equal(
+ (built.sources.satellite as { attribution?: string }).attribution,
+ openSatelliteAttribution
+ );
+ assert.equal(
+ (built.sources.fallback as { attribution?: string }).attribution,
+ openSatelliteFallbackAttribution
+ );
+ assert.equal((built.sources.other as { attribution?: string }).attribution, undefined);
+ });
+});
diff --git a/website/src/lib/components/map/style.ts b/website/src/lib/components/map/style.ts
index 1696977b3..062dad111 100644
--- a/website/src/lib/components/map/style.ts
+++ b/website/src/lib/components/map/style.ts
@@ -16,6 +16,12 @@ import {
} from '$lib/data/layers';
import { getLayers, getOpacityPaint, prefixStyle } from '$lib/components/map/layer-control/utils';
import { i18n } from '$lib/i18n/i18n.svelte';
+import {
+ OPEN_SATELLITE_FALLBACK_PROTOCOL,
+ OPEN_SATELLITE_PROTOCOL,
+ openSatelliteAttribution,
+ openSatelliteFallbackAttribution,
+} from '$lib/components/map/open-satellite';
const { currentBasemap, currentOverlays, customLayers, opacities, terrainSource, distanceUnits } =
settings;
@@ -123,6 +129,18 @@ export class StyleManager {
) {
src.url = src.url.replace(maptilerKeyPlaceHolder, this._maptilerKey);
}
+ if (src && typeof src === 'object' && 'tiles' in src) {
+ // the credits of the open satellite imagery, kept with its code
+ if (src.tiles?.some((url) => url.startsWith(`${OPEN_SATELLITE_PROTOCOL}://`))) {
+ src.attribution = openSatelliteAttribution;
+ } else if (
+ src.tiles?.some((url) =>
+ url.startsWith(`${OPEN_SATELLITE_FALLBACK_PROTOCOL}://`)
+ )
+ ) {
+ src.attribution = openSatelliteFallbackAttribution;
+ }
+ }
}
} catch (e) {
console.error(e instanceof Error ? e.message : e);