adaptative attribution

This commit is contained in:
vcoppe committed 2026-12-04 09:47:48 +01:00
1 parent 4b5b6b8a20
commit 22a269a6dc
5 files changed
+264 -92

No files matched your search

+5 -1
View File
@@ -10,7 +10,10 @@ 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';
import {
registerOpenSatelliteProtocol,
trackOpenSatelliteAttribution,
} from '$lib/components/map/open-satellite';
const { treeFileView, elevationProfile, bottomPanelSize, rightPanelSize, distanceUnits } = settings;
@@ -71,6 +74,7 @@ export class MapLibreGLMap {
maxPitch: 90,
});
this.layerEventManager = new MapLayerEventManager(map);
trackOpenSatelliteAttribution(map);
map.addControl(
new maplibregl.NavigationControl({
visualizePitch: true,
@@ -3,7 +3,14 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { fallbackNeeded, planTile, type CountryTiles } from './open-satellite';
import * as maplibregl from 'maplibre-gl';
import {
attributionsOf,
fallbackNeeded,
planTile,
trackOpenSatelliteAttribution,
type CountryTiles,
} from './open-satellite';
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
@@ -206,3 +213,97 @@ describe('fallbackNeeded', () => {
assert.equal(await fallbackNeeded(12, 2134, 1430, tiles), true);
});
});
describe('attributionsOf', () => {
const credits = async (tilesInView: [number, number, number][]) => {
const { open, fallback } = await attributionsOf(
tilesInView.map(([z, x, y]) => ({ z, x, y })),
savedTiles().tiles
);
return { open: open.replace(/<[^>]*>/g, ''), fallback: fallback.replace(/<[^>]*>/g, '') };
};
it('credits only the imagery of the whole world up to zoom 12', async () => {
assert.deepEqual(await credits([tile(6.63, 46.52, 12)]), {
open: 'IGN-F/Géoplateforme',
fallback: '',
});
});
it('credits the countries in view, each once', async () => {
// Paris, twice, and Basel
assert.deepEqual(
await credits([tile(2.35, 48.85, 15), tile(2.35, 48.85, 14), [13, 4268, 2861]]),
{ open: 'swisstopo, IGN-F/Géoplateforme', fallback: '© MapTiler' }
);
assert.equal((await credits([tile(-94.6075, 39.11, 13)])).open, 'USDA');
});
it('credits only the fallback far from every country', async () => {
assert.deepEqual(await credits([tile(-0.12, 51.5, 14)]), {
open: '',
fallback: '© MapTiler',
});
});
it('credits the imagery of the whole world for the far tiles of a tilted map', async () => {
assert.deepEqual(await credits([tile(-0.12, 51.5, 14), tile(-0.12, 51.5, 11)]), {
open: 'IGN-F/Géoplateforme',
fallback: '© MapTiler',
});
});
});
describe('trackOpenSatelliteAttribution', () => {
it('changes the credits of the sources with the view, and has the control read them', async () => {
const map = new (class extends maplibregl.Evented {})() as unknown as maplibregl.Map;
const fired: string[] = [];
const sources: Record<string, { tiles: string[]; attribution?: string }> = {};
const add = (id: string, protocol: string) => {
const spec = { type: 'raster', tiles: [`${protocol}://{z}/{x}/{y}`] };
const tell = () =>
map.fire(
new maplibregl.MapSourceDataEvent('sourcedata', {
sourceDataType: 'metadata',
sourceId: id,
source: spec as maplibregl.RasterSourceSpecification,
})
);
sources[id] = Object.assign({}, spec, {
fire: (event: maplibregl.MapSourceDataEvent) => {
assert.equal(event.sourceDataType, 'metadata');
fired.push(id);
tell();
},
});
tell();
};
let view = tile(-0.12, 51.5, 10);
Object.assign(map, {
getSource: (id: string) => sources[id],
coveringTiles: () => [{ canonical: { z: view[0], x: view[1], y: view[2] } }],
});
const settled = () => new Promise((resolve) => setTimeout(resolve, 50));
trackOpenSatelliteAttribution(map);
add('satellite', 'opensat');
add('fallback', 'opensat-fallback');
await settled();
assert.match(sources.satellite.attribution ?? '', /^<a [^>]*>IGN-F\/Géoplateforme<\/a>$/);
assert.equal(sources.fallback.attribution, undefined);
assert.deepEqual(fired, ['satellite']);
// London, only on the fallback
view = tile(-0.12, 51.5, 14);
map.fire('moveend');
await settled();
assert.equal(sources.satellite.attribution, '');
assert.match(sources.fallback.attribution ?? '', /MapTiler/);
// nothing to change
fired.length = 0;
map.fire('moveend');
await settled();
assert.deepEqual(fired, []);
});
});
+156 -39
View File
@@ -12,13 +12,15 @@ import { PbfReader } from 'pbf';
* something to see.
*/
export const OPEN_SATELLITE_PROTOCOL = 'opensat';
const OPEN_SATELLITE_PROTOCOL = 'opensat';
type TileUrl = (z: number, x: number, y: number) => string;
type ImagerySource = {
/** ISO code of the country, or of its state, in the tileset of the countries */
id: string;
/** Its credit, shown while its imagery is in view. */
attribution: string;
url: TileUrl;
/** Above it, the tile of this zoom level is scaled up. */
maxzoom: number;
@@ -54,6 +56,9 @@ const wms =
return `${base}&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&STYLES=&CRS=EPSG:3857&WIDTH=${pixels}&HEIGHT=${pixels}&BBOX=${tileBounds(z, x, y).join(',')}`;
};
const ignAttribution =
'<a href="https://geoservices.ign.fr/" target="_blank">IGN-F/Géoplateforme</a>';
const ignOrthophotos = 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}'
);
@@ -62,7 +67,12 @@ const ignOrthophotos = xyz(
* Up to zoom 12, IGN's orthophotos cover the whole world with a mosaic of satellite images: all
* tiles come from it there, and the national sources and the commercial fallback only above.
*/
const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
const world: ImagerySource = {
id: 'world',
attribution: ignAttribution,
url: ignOrthophotos,
maxzoom: 12,
};
/** For an image server of ArcGIS: the tile as an image of its bounds in Web Mercator. */
const arcgis =
@@ -87,6 +97,7 @@ const naipStates = [
const sources: ImagerySource[] = [
{
id: 'CH',
attribution: '<a href="https://www.swisstopo.admin.ch/" target="_blank">swisstopo</a>',
url: xyz(
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
),
@@ -94,11 +105,13 @@ const sources: ImagerySource[] = [
},
{
id: 'FR',
attribution: ignAttribution,
url: ignOrthophotos,
maxzoom: 19,
},
{
id: 'ES',
attribution: 'PNOA © <a href="https://www.ign.es/" target="_blank">IGN España</a>',
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}'
),
@@ -106,6 +119,7 @@ const sources: ImagerySource[] = [
},
{
id: 'AT',
attribution: '<a href="https://basemap.at/" target="_blank">basemap.at</a>',
url: xyz(
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
),
@@ -113,6 +127,7 @@ const sources: ImagerySource[] = [
},
{
id: 'NL',
attribution: '<a href="https://www.pdok.nl/" target="_blank">PDOK</a>',
url: xyz(
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
),
@@ -120,6 +135,7 @@ const sources: ImagerySource[] = [
},
{
id: 'LU',
attribution: '<a href="https://geoportail.lu/" target="_blank">geoportail.lu</a>',
url: xyz(
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
),
@@ -127,6 +143,7 @@ const sources: ImagerySource[] = [
},
{
id: 'CZ',
attribution: '<a href="https://cuzk.gov.cz/" target="_blank">ČÚZK</a>',
url: xyz(
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
),
@@ -134,6 +151,7 @@ const sources: ImagerySource[] = [
},
{
id: 'BE',
attribution: '<a href="https://www.ngi.be/" target="_blank">NGI/IGN</a>',
url: xyz(
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
),
@@ -141,6 +159,7 @@ const sources: ImagerySource[] = [
},
{
id: 'PL',
attribution: '<a href="https://www.geoportal.gov.pl/" target="_blank">GUGiK</a>',
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}'
),
@@ -149,6 +168,7 @@ const sources: ImagerySource[] = [
{
// mainland Portugal only, as in the tileset of the countries
id: 'PT',
attribution: '<a href="https://www.dgterritorio.gov.pt/" target="_blank">DGT</a>',
url: wms(
'https://cartografia.dgterritorio.gov.pt/wms/ortos2025?LAYERS=Ortos2025-RGB&FORMAT=image/jpeg',
// blank at zoom 13
@@ -158,6 +178,8 @@ const sources: ImagerySource[] = [
},
{
id: 'DK',
attribution:
'GeoDanmark © <a href="https://klimadatastyrelsen.dk/" target="_blank">Klimadatastyrelsen</a>',
url: xyz(
'https://wmts.datafordeler.dk/GeoDanmarkOrto/orto_foraar_webm/1.0.0/WMTS/orto_foraar_webm/default/DFD_GoogleMapsCompatible/{z}/{y}/{x}.jpg?apikey=pDSRuC5YLFT3jHf4XbaWDGSa9Td4TfYiGiB7YfhCKikJhZE6xibJAlaNp1KpDAzHdDss9DSKdq3nNoT2UFU3cmecaLrcRNTOc'
),
@@ -165,6 +187,8 @@ const sources: ImagerySource[] = [
},
{
id: 'NZ',
attribution:
'© <a href="https://www.linz.govt.nz/linz-copyright" target="_blank">LINZ CC BY 4.0</a> © <a href="https://www.linz.govt.nz/data/linz-data/linz-basemaps/data-attribution" target="_blank">Imagery Basemap contributors</a>',
url: xyz(
'https://basemaps.linz.govt.nz/v1/tiles/aerial/WebMercatorQuad/{z}/{x}/{y}.webp?api=d01fbtg0ar23gctac5m0jgyy2ds'
),
@@ -174,11 +198,14 @@ const sources: ImagerySource[] = [
// tiles
{
id: 'DE-BY',
attribution:
'© <a href="https://geodaten.bayern.de/" target="_blank">Bayerische Vermessungsverwaltung</a>',
url: xyz('https://wmtsod1.bayernwolke.de/wmts/by_dop/smerc/{z}/{x}/{y}'),
maxzoom: 19,
},
{
id: 'DE-MV',
attribution: '© <a href="https://www.laiv-mv.de/" target="_blank">GeoBasis-DE/M-V</a>',
// its tile matrices are numbered from zoom 5
url: (z, x, y) =>
`https://www.geodaten-mv.de/dienste/dop_wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=mv_dop&STYLE=default&FORMAT=image/png&TILEMATRIXSET=GoogleMapsCompatible&TILEMATRIX=${String(z - 5).padStart(2, '0')}&TILEROW=${y}&TILECOL=${x}`,
@@ -186,6 +213,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-BB',
attribution: '© <a href="https://geobasis-bb.de/" target="_blank">GeoBasis-DE/LGB</a>',
url: wms(
'https://isk.geobasis-bb.de/mapproxy/dop20c/service/wms?LAYERS=bebb_dop20c&FORMAT=image/jpeg'
),
@@ -194,6 +222,8 @@ const sources: ImagerySource[] = [
{
// the service of Brandenburg, which has Berlin too
id: 'DE-BE',
attribution:
'© <a href="https://www.berlin.de/sen/sbw/stadtdaten/geoportal/" target="_blank">Geoportal Berlin</a>',
url: wms(
'https://isk.geobasis-bb.de/mapproxy/dop20c/service/wms?LAYERS=bebb_dop20c&FORMAT=image/jpeg'
),
@@ -202,6 +232,8 @@ const sources: ImagerySource[] = [
{
// Bremen and Bremerhaven
id: 'DE-HB',
attribution:
'© <a href="https://www.geo.bremen.de/" target="_blank">Landesamt GeoInformation Bremen</a>',
url: wms(
'https://geodienste.bremen.de/wms_dop_lb?LAYERS=dop10_2025_HB,dop10_2025_BHV&FORMAT=image/jpeg'
),
@@ -210,6 +242,7 @@ const sources: ImagerySource[] = [
{
// without its islands in the North Sea, as in the tileset of the countries
id: 'DE-HH',
attribution: '© <a href="https://www.hamburg.de/" target="_blank">LGV Hamburg</a>',
url: wms(
'https://geodienste.hamburg.de/wms_dop_zeitreihe_unbelaubt?LAYERS=dop_zeitreihe_unbelaubt&FORMAT=image/jpeg'
),
@@ -217,6 +250,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-HE',
attribution: '© <a href="https://hvbg.hessen.de/" target="_blank">HVBG</a>',
url: wms(
'https://www.gds-srv.hessen.de/cgi-bin/lika-services/ogc-free-images.ows?LAYERS=he_dop_rgb&FORMAT=image/jpeg'
),
@@ -224,6 +258,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-NI',
attribution: '© <a href="https://www.lgln.niedersachsen.de/" target="_blank">LGLN</a>',
url: wms(
'https://opendata.lgln.niedersachsen.de/doorman/noauth/dop_wms?LAYERS=ni_dop20&FORMAT=image/jpeg'
),
@@ -231,11 +266,15 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-NW',
attribution:
'© <a href="https://www.bezreg-koeln.nrw.de/" target="_blank">Geobasis NRW</a>',
url: wms('https://www.wms.nrw.de/geobasis/wms_nw_dop?LAYERS=nw_dop_rgb&FORMAT=image/jpeg'),
maxzoom: 19,
},
{
id: 'DE-RP',
attribution:
'© <a href="https://lvermgeo.rlp.de/" target="_blank">GeoBasis-DE/LVermGeoRP</a>',
url: wms(
'https://geo4.service24.rlp.de/wms/rp_dop20.fcgi?LAYERS=rp_dop20&FORMAT=image/jpeg'
),
@@ -243,6 +282,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-SL',
attribution: '© <a href="https://geoportal.saarland.de/" target="_blank">LVGL Saarland</a>',
url: wms(
'https://geoportal.saarland.de/freewms/truedop?LAYERS=sl_dop20_rgb&FORMAT=image/jpeg'
),
@@ -250,6 +290,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-SN',
attribution: '© <a href="https://www.geosn.sachsen.de/" target="_blank">GeoSN</a>',
url: wms(
'https://geodienste.sachsen.de/wms_geosn_dop-rgb/guest?LAYERS=sn_dop_020&FORMAT=image/jpeg'
),
@@ -257,6 +298,8 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-ST',
attribution:
'© <a href="https://www.lvermgeo.sachsen-anhalt.de/" target="_blank">GeoBasis-DE/LVermGeo LSA</a>',
url: wms(
'https://www.geodatenportal.sachsen-anhalt.de/wss/service/ST_LVermGeo_DOP_WMS_OpenData/guest?LAYERS=lsa_lvermgeo_dop20_2&FORMAT=image/jpeg'
),
@@ -264,6 +307,8 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-SH',
attribution:
'© <a href="https://www.schleswig-holstein.de/" target="_blank">GeoBasis-DE/LVermGeo SH</a>',
url: wms(
'https://dienste.gdi-sh.de/WMS_SH_DOP20col_OpenGBD?LAYERS=sh_dop20_rgb&FORMAT=image/jpeg'
),
@@ -272,6 +317,7 @@ const sources: ImagerySource[] = [
},
{
id: 'DE-TH',
attribution: '© <a href="https://geoportal.thueringen.de/" target="_blank">GDI-Th</a>',
url: wms(
'https://www.geoproxy.geoportal-th.de/geoproxy/services/DOP?LAYERS=th_dop&FORMAT=image/jpeg'
),
@@ -280,9 +326,17 @@ const sources: ImagerySource[] = [
// The United States, by state: Alaska, Arizona, Colorado, Delaware, Hawaii and Washington are
// left to the fallback. The NAIP has none of Maryland and the District of Columbia, and blurred
// images of Oregon and Virginia.
...naipStates.map((state) => ({ id: `US-${state}`, url: naip, maxzoom: 18, holes: true })),
...naipStates.map((state) => ({
id: `US-${state}`,
attribution: '<a href="https://naip-usdaonline.hub.arcgis.com/" target="_blank">USDA</a>',
url: naip,
maxzoom: 18,
holes: true,
})),
{
id: 'US-OR',
attribution:
'<a href="https://www.oregon.gov/eis/geo/" target="_blank">State of Oregon</a>',
url: arcgis(
'https://imagery.oregonexplorer.info/arcgis/rest/services/OSIP_2024/OSIP_2024_WM/ImageServer'
),
@@ -291,6 +345,7 @@ const sources: ImagerySource[] = [
},
{
id: 'US-VA',
attribution: '<a href="https://vgin.vdem.virginia.gov/" target="_blank">VGIN</a>',
url: xyz(
'https://vginmaps.vdem.virginia.gov/arcgis/rest/services/VBMP_Imagery/MostRecentImagery_WGS/MapServer/tile/{z}/{y}/{x}'
),
@@ -299,6 +354,7 @@ const sources: ImagerySource[] = [
},
{
id: 'US-MD',
attribution: '<a href="https://imap.maryland.gov/" target="_blank">MD iMAP</a>',
url: arcgis(
'https://mdgeodata.md.gov/imagery/rest/services/SixInch/SixInchImagery/ImageServer'
),
@@ -307,6 +363,7 @@ const sources: ImagerySource[] = [
},
{
id: 'US-DC',
attribution: '© <a href="https://opendata.dc.gov/" target="_blank">DC GIS CC BY 4.0</a>',
url: wms(
'https://imagery.dcgis.dc.gov/dcgis/services/Ortho/Ortho_2025/ImageServer/WMSServer?LAYERS=Ortho_2025&FORMAT=image/jpeg'
),
@@ -314,40 +371,13 @@ const sources: ImagerySource[] = [
},
];
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.dgterritorio.gov.pt/" target="_blank">DGT</a>',
'GeoDanmark © <a href="https://klimadatastyrelsen.dk/" target="_blank">Klimadatastyrelsen</a>',
'© <a href="https://www.linz.govt.nz/linz-copyright" target="_blank">LINZ CC BY 4.0</a> © <a href="https://www.linz.govt.nz/data/linz-data/linz-basemaps/data-attribution" target="_blank">Imagery Basemap contributors</a>',
'© <a href="https://geodaten.bayern.de/" target="_blank">Bayerische Vermessungsverwaltung</a>',
'© <a href="https://geobasis-bb.de/" target="_blank">GeoBasis-DE/LGB</a>',
'© <a href="https://www.berlin.de/sen/sbw/stadtdaten/geoportal/" target="_blank">Geoportal Berlin</a>',
'© <a href="https://www.geo.bremen.de/" target="_blank">Landesamt GeoInformation Bremen</a>',
'© <a href="https://www.hamburg.de/" target="_blank">LGV Hamburg</a>',
'© <a href="https://hvbg.hessen.de/" target="_blank">HVBG</a>',
'© <a href="https://www.laiv-mv.de/" target="_blank">GeoBasis-DE/M-V</a>',
'© <a href="https://www.lgln.niedersachsen.de/" target="_blank">LGLN</a>',
'© <a href="https://www.bezreg-koeln.nrw.de/" target="_blank">Geobasis NRW</a>',
'© <a href="https://lvermgeo.rlp.de/" target="_blank">GeoBasis-DE/LVermGeoRP</a>',
'© <a href="https://geoportal.saarland.de/" target="_blank">LVGL Saarland</a>',
'© <a href="https://www.geosn.sachsen.de/" target="_blank">GeoSN</a>',
'© <a href="https://www.lvermgeo.sachsen-anhalt.de/" target="_blank">GeoBasis-DE/LVermGeo LSA</a>',
'© <a href="https://www.schleswig-holstein.de/" target="_blank">GeoBasis-DE/LVermGeo SH</a>',
'© <a href="https://geoportal.thueringen.de/" target="_blank">GDI-Th</a>',
'<a href="https://naip-usdaonline.hub.arcgis.com/" target="_blank">USDA</a>',
'<a href="https://www.oregon.gov/eis/geo/" target="_blank">State of Oregon</a>',
'<a href="https://vgin.vdem.virginia.gov/" target="_blank">VGIN</a>',
'<a href="https://imap.maryland.gov/" target="_blank">MD iMAP</a>',
'© <a href="https://opendata.dc.gov/" target="_blank">DC GIS CC BY 4.0</a>',
].join(', ');
/** The credits of the sources, each once, in the order of the list. */
function creditsOf(used: Iterable<ImagerySource>) {
const credits = new Set(Array.from(used, (source) => source.attribution));
return [...new Set(sources.map((source) => source.attribution))]
.filter((credit) => credits.has(credit))
.join(', ');
}
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
@@ -678,9 +708,9 @@ export async function loadTile(
// 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';
const OPEN_SATELLITE_FALLBACK_PROTOCOL = 'opensat-fallback';
export const openSatelliteFallbackAttribution =
const fallbackAttribution =
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>';
const fallbackUrl = (maptilerKey: string) =>
@@ -715,6 +745,93 @@ export async function loadFallbackTile(
return await response.arrayBuffer();
}
// The credits of the imagery in view
type TileId = { z: number; x: number; y: number };
/**
* The credits of the imagery of the tiles of 256 pixels, for the layer of the open imagery and
* for the fallback. The fallback is credited above zoom 12 even where the countries cover
* everything, as it also stands in for what their sources do not give.
*/
export async function attributionsOf(
tilesInView: TileId[],
tiles: CountryTiles = fetchCountryTile
): Promise<{ open: string; fallback: string }> {
const above = tilesInView.filter(({ z }) => z > world.maxzoom);
const plans = await Promise.all(above.map(({ z, x, y }) => planTile(z, x, y, tiles)));
const used = plans.flatMap((plan) => plan.parts.map((part) => part.source));
if (above.length < tilesInView.length) used.push(world);
return {
open: creditsOf(used),
fallback: above.length > 0 ? fallbackAttribution : '',
};
}
/** MapLibre copies the credit of the style to the source, but leaves it out of its type. */
type CreditedSource = maplibregl.RasterTileSource & { attribution?: string };
/**
* Changes the credit of the source without reloading it: the attribution control reads it from
* the source, not from the style, each time a source tells that its metadata is there.
*/
function setAttribution(source: CreditedSource, attribution: string) {
if ((source.attribution ?? '') === attribution) return;
source.attribution = attribution;
source.fire(new maplibregl.MapSourceDataEvent('data', { sourceDataType: 'metadata' }));
}
/**
* Keeps the credits of the open satellite basemap to those of the imagery in view. Its style has
* none: nothing is credited until they are known.
*/
export function trackOpenSatelliteAttribution(map: maplibregl.Map) {
/** The ids of the sources of the basemap, by protocol, once they have been on the map. */
const sourceIds = new Map<string, string>();
const usesProtocol = (tiles: string[] | undefined, protocol: string) =>
!!tiles?.some((url) => url.startsWith(`${protocol}://`));
const sourceOf = (protocol: string) => {
const id = sourceIds.get(protocol);
const source = id === undefined ? undefined : map.getSource<CreditedSource>(id);
// another basemap can have a source with the same id
return source && usesProtocol(source.tiles, protocol) ? source : undefined;
};
let lastUpdate = 0;
const update = async () => {
const current = ++lastUpdate;
const open = sourceOf(OPEN_SATELLITE_PROTOCOL);
if (!open) return;
// the same tiles as MapLibre takes for the source, with the relief in 3D
const options = {
tileSize: open.tileSize,
minzoom: open.minzoom,
maxzoom: open.maxzoom,
roundZoom: open.roundZoom,
terrain: map.terrain,
};
const tilesInView = map.coveringTiles(options).map((tile) => tile.canonical);
const credits = await attributionsOf(tilesInView);
// the map has moved or changed its style since
if (current !== lastUpdate) return;
setAttribution(open, credits.open);
const fallback = sourceOf(OPEN_SATELLITE_FALLBACK_PROTOCOL);
if (fallback) setAttribution(fallback, credits.fallback);
};
map.on('moveend', update);
map.on('resize', update);
// a source just added, without credit
map.on('sourcedata', ({ sourceDataType, sourceId, source }) => {
if (sourceDataType !== 'metadata' || source?.type !== 'raster') return;
for (const protocol of [OPEN_SATELLITE_PROTOCOL, OPEN_SATELLITE_FALLBACK_PROTOCOL]) {
if (usesProtocol(source.tiles, protocol)) {
sourceIds.set(protocol, sourceId);
update();
}
}
});
}
function tileOf(url: string) {
const match = url.match(/(\d+)\/(\d+)\/(\d+)$/);
if (!match) throw new Error(`Invalid tile URL: ${url}`);
+1 -33
View File
@@ -3,11 +3,10 @@ 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 { basemaps, overlays, type LayerTreeType } from '$lib/data/layers';
import { 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';
@@ -219,34 +218,3 @@ 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<MapLibreMap | null>(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);
});
});
-18
View File
@@ -16,12 +16,6 @@ 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;
@@ -129,18 +123,6 @@ 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);