mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-12-06 10:34:13 +00:00
us sources
This commit is contained in:
1 parent
cc97f03e29
commit
4b5b6b8a20
6 files changed
+163
-31
No files matched your search
@@ -137,6 +137,35 @@ describe('planTile', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('takes the states of the United States with the same imagery as one', async () => {
|
||||
const { tiles } = savedTiles();
|
||||
// Kansas City, in Kansas and Missouri, both from the NAIP
|
||||
const { parts, fallback } = await planTile(...tile(-94.6075, 39.11, 13), tiles);
|
||||
assert.deepEqual(
|
||||
parts.map((part) => part.relation),
|
||||
['full']
|
||||
);
|
||||
assert.equal(fallback, false);
|
||||
});
|
||||
|
||||
it('takes other states from their own agencies', async () => {
|
||||
const { tiles } = savedTiles();
|
||||
// Washington DC
|
||||
assert.deepEqual(await plan(tile(-77.036, 38.897, 16), tiles), {
|
||||
parts: ['US-DC:full'],
|
||||
fallback: false,
|
||||
});
|
||||
// Portland, and the Columbia, with Washington, which is not in the patchwork, to the north
|
||||
assert.deepEqual(await plan(tile(-122.68, 45.59, 16), tiles), {
|
||||
parts: ['US-OR:full'],
|
||||
fallback: false,
|
||||
});
|
||||
assert.deepEqual(await plan([13, 1305, 2927], tiles), {
|
||||
parts: ['US-OR:partial'],
|
||||
fallback: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('asks for a tile of the countries once for all the tiles of imagery inside it', async () => {
|
||||
const { asked, tiles } = savedTiles();
|
||||
// around Lausanne, which no other test asks for
|
||||
|
||||
@@ -27,6 +27,8 @@ type ImagerySource = {
|
||||
* is left to the fallback.
|
||||
*/
|
||||
httpsOnly?: boolean;
|
||||
/** Its images are in PNG, with transparency, where part of them is missing. */
|
||||
holes?: boolean;
|
||||
};
|
||||
|
||||
const xyz =
|
||||
@@ -34,6 +36,13 @@ const xyz =
|
||||
(z, x, y) =>
|
||||
template.replace('{z}', String(z)).replace('{x}', String(x)).replace('{y}', String(y));
|
||||
|
||||
/** The bounds of the tile in Web Mercator: west, south, east and north. */
|
||||
function tileBounds(z: number, x: number, y: number) {
|
||||
const half = 20037508.342789244;
|
||||
const size = (2 * half) / 2 ** z;
|
||||
return [x * size - half, half - (y + 1) * size, (x + 1) * size - half, half - y * size];
|
||||
}
|
||||
|
||||
/**
|
||||
* For a WMS: the tile as an image of its bounds in Web Mercator. A WMS that draws nothing below
|
||||
* the scale of zoom `minzoom` is asked for a larger image there, at that scale.
|
||||
@@ -41,16 +50,8 @@ const xyz =
|
||||
const wms =
|
||||
(base: string, minzoom = 0): TileUrl =>
|
||||
(z, x, y) => {
|
||||
const half = 20037508.342789244;
|
||||
const size = (2 * half) / 2 ** z;
|
||||
const pixels = 256 * 2 ** Math.max(0, minzoom - z);
|
||||
const bbox = [
|
||||
x * size - half,
|
||||
half - (y + 1) * size,
|
||||
(x + 1) * size - half,
|
||||
half - y * size,
|
||||
];
|
||||
return `${base}&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&STYLES=&CRS=EPSG:3857&WIDTH=${pixels}&HEIGHT=${pixels}&BBOX=${bbox.join(',')}`;
|
||||
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 ignOrthophotos = xyz(
|
||||
@@ -63,6 +64,25 @@ const ignOrthophotos = xyz(
|
||||
*/
|
||||
const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
|
||||
|
||||
/** For an image server of ArcGIS: the tile as an image of its bounds in Web Mercator. */
|
||||
const arcgis =
|
||||
(base: string): TileUrl =>
|
||||
(z, x, y) =>
|
||||
`${base}/exportImage?f=image&format=jpgpng&bboxSR=3857&imageSR=3857&size=256,256&bbox=${tileBounds(z, x, y).join(',')}`;
|
||||
|
||||
const naip = arcgis(
|
||||
'https://apps.geo.fpac.usda.gov/geo-imagery/rest/services/naip/conus_naip/ImageServer'
|
||||
);
|
||||
|
||||
/** The states whose imagery is that of the NAIP, from the USDA. */
|
||||
// prettier-ignore
|
||||
const naipStates = [
|
||||
'AL', 'AR', 'CA', 'CT', 'FL', 'GA', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY',
|
||||
'LA', 'MA', 'ME', 'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH',
|
||||
'NJ', 'NM', 'NV', 'NY', 'OH', 'OK', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX',
|
||||
'UT', 'VT', 'WI', 'WV', 'WY',
|
||||
];
|
||||
|
||||
/** In order of priority, the first one covering a point is used. */
|
||||
const sources: ImagerySource[] = [
|
||||
{
|
||||
@@ -257,6 +277,41 @@ const sources: ImagerySource[] = [
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
// 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 })),
|
||||
{
|
||||
id: 'US-OR',
|
||||
url: arcgis(
|
||||
'https://imagery.oregonexplorer.info/arcgis/rest/services/OSIP_2024/OSIP_2024_WM/ImageServer'
|
||||
),
|
||||
maxzoom: 19,
|
||||
holes: true,
|
||||
},
|
||||
{
|
||||
id: 'US-VA',
|
||||
url: xyz(
|
||||
'https://vginmaps.vdem.virginia.gov/arcgis/rest/services/VBMP_Imagery/MostRecentImagery_WGS/MapServer/tile/{z}/{y}/{x}'
|
||||
),
|
||||
maxzoom: 19,
|
||||
holes: true,
|
||||
},
|
||||
{
|
||||
id: 'US-MD',
|
||||
url: arcgis(
|
||||
'https://mdgeodata.md.gov/imagery/rest/services/SixInch/SixInchImagery/ImageServer'
|
||||
),
|
||||
maxzoom: 19,
|
||||
holes: true,
|
||||
},
|
||||
{
|
||||
id: 'US-DC',
|
||||
url: wms(
|
||||
'https://imagery.dcgis.dc.gov/dcgis/services/Ortho/Ortho_2025/ImageServer/WMSServer?LAYERS=Ortho_2025&FORMAT=image/jpeg'
|
||||
),
|
||||
maxzoom: 19,
|
||||
},
|
||||
];
|
||||
|
||||
export const openSatelliteAttribution = [
|
||||
@@ -287,6 +342,11 @@ export const openSatelliteAttribution = [
|
||||
'© <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(', ');
|
||||
|
||||
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
|
||||
@@ -389,7 +449,10 @@ function signedArea(ring: Ring) {
|
||||
return area / 2;
|
||||
}
|
||||
|
||||
/** The polygons of the countries with imagery in the tile, cut to it, with their area. */
|
||||
/**
|
||||
* The polygons of the countries with imagery in the tile, cut to it, with their area. Neighbours
|
||||
* with the same imagery, such as most of the United States, are taken as one.
|
||||
*/
|
||||
function countriesInTile(
|
||||
bytes: ArrayBuffer,
|
||||
z: number,
|
||||
@@ -402,7 +465,7 @@ function countriesInTile(
|
||||
const scale = (TILE_SIZE * 2 ** d) / layer.extent;
|
||||
const offsetX = (x - ((x >> d) << d)) * TILE_SIZE;
|
||||
const offsetY = (y - ((y >> d) << d)) * TILE_SIZE;
|
||||
const countries = [];
|
||||
const countries: { source: ImagerySource; rings: Ring[]; area: number }[] = [];
|
||||
for (let i = 0; i < layer.length; i++) {
|
||||
const feature = layer.feature(i);
|
||||
const source = sourceByCountry.get(String(feature.properties.country));
|
||||
@@ -415,7 +478,14 @@ function countriesInTile(
|
||||
.filter((ring) => ring.length >= 3);
|
||||
const area = rings.reduce((sum, ring) => sum + signedArea(ring), 0);
|
||||
// less than a pixel: a polygon of the tile of the countries outside this one
|
||||
if (area >= 1) countries.push({ source, rings, area });
|
||||
if (area < 1) continue;
|
||||
const same = countries.find((country) => country.source.url === source.url);
|
||||
if (same) {
|
||||
same.rings.push(...rings);
|
||||
same.area += area;
|
||||
} else {
|
||||
countries.push({ source, rings, area });
|
||||
}
|
||||
}
|
||||
return countries;
|
||||
}
|
||||
@@ -461,18 +531,32 @@ async function isBlank(bytes: ArrayBuffer) {
|
||||
}
|
||||
}
|
||||
|
||||
type TileImage = { image: ImageBitmap; sx: number; sy: number; size: number; holes: boolean };
|
||||
|
||||
function isPng(bytes: ArrayBuffer) {
|
||||
return new Uint8Array(bytes, 0, 1)[0] === 0x89;
|
||||
}
|
||||
|
||||
/** 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,
|
||||
{ url, maxzoom, holes }: Pick<ImagerySource, 'url' | 'maxzoom' | 'holes'>,
|
||||
z: number,
|
||||
x: number,
|
||||
y: number,
|
||||
signal: AbortSignal
|
||||
): Promise<{ image: ImageBitmap; sx: number; sy: number; size: number } | null> {
|
||||
): Promise<TileImage | null> {
|
||||
const d = Math.max(0, z - maxzoom);
|
||||
const bytes = await fetchBytes(url(z - d, x >> d, y >> d), signal);
|
||||
if (!bytes) return null;
|
||||
return bytes && decodeImage(bytes, d, x, y, !!holes && isPng(bytes));
|
||||
}
|
||||
|
||||
async function decodeImage(
|
||||
bytes: ArrayBuffer,
|
||||
d: number,
|
||||
x: number,
|
||||
y: number,
|
||||
holes: boolean
|
||||
): Promise<TileImage | null> {
|
||||
try {
|
||||
const image = await createImageBitmap(new Blob([bytes]));
|
||||
const size = image.width / 2 ** d;
|
||||
@@ -481,6 +565,7 @@ async function fetchImage(
|
||||
sx: (x - ((x >> d) << d)) * size,
|
||||
sy: (y - ((y >> d) << d)) * size,
|
||||
size,
|
||||
holes,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
@@ -536,14 +621,22 @@ function transparentTile() {
|
||||
return canvas.transferToImageBitmap();
|
||||
}
|
||||
|
||||
function drawImage(context: OffscreenCanvasRenderingContext2D, tile: TileImage) {
|
||||
const { image, sx, sy, size } = tile;
|
||||
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* What the source of a country does not give is taken from the commercial fallback, whose layer
|
||||
* below has nothing there.
|
||||
*/
|
||||
export async function loadTile(
|
||||
z: number,
|
||||
x: number,
|
||||
y: number,
|
||||
maptilerKey: string,
|
||||
signal: AbortSignal
|
||||
): Promise<ArrayBuffer | ImageBitmap> {
|
||||
if (z <= world.maxzoom) {
|
||||
@@ -552,26 +645,34 @@ export async function loadTile(
|
||||
const { parts } = await planTile(z, x, y);
|
||||
if (parts.length === 0) return transparentTile();
|
||||
|
||||
// a single tile as it is, without drawing it again
|
||||
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();
|
||||
let images: (TileImage | null)[];
|
||||
const { source, relation } = parts[0];
|
||||
if (parts.length === 1 && relation === 'full' && z <= source.maxzoom) {
|
||||
const bytes = await fetchBytes(source.url(z, x, y), signal);
|
||||
const holes = !!bytes && !!source.holes && isPng(bytes);
|
||||
// a single tile as it is, without drawing it again
|
||||
if (bytes && !holes) return bytes;
|
||||
images = [bytes && (await decodeImage(bytes, 0, x, y, holes))];
|
||||
} else {
|
||||
images = await Promise.all(parts.map((p) => fetchImage(p.source, z, x, y, signal)));
|
||||
}
|
||||
|
||||
const images = await Promise.all(
|
||||
parts.map((p) => fetchImage(p.source.url, p.source.maxzoom, z, x, y, signal))
|
||||
);
|
||||
// a quarter of the tile of 512 pixels of the zoom level below
|
||||
const fallback = images.some((image) => !image || image.holes)
|
||||
? await fetchImage({ url: fallbackUrl(maptilerKey), maxzoom: z - 1 }, z, x, y, signal)
|
||||
: null;
|
||||
const canvas = new OffscreenCanvas(TILE_SIZE, TILE_SIZE);
|
||||
const context = canvas.getContext('2d')!;
|
||||
parts.forEach((p, i) => {
|
||||
const result = images[i];
|
||||
if (!result) return;
|
||||
const image = images[i];
|
||||
context.save();
|
||||
if (p.relation === 'partial') clipTo(context, p.rings);
|
||||
const { image, sx, sy, size } = result;
|
||||
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
|
||||
if (fallback && (!image || image.holes)) drawImage(context, fallback);
|
||||
if (image) drawImage(context, image);
|
||||
context.restore();
|
||||
image.close();
|
||||
image?.image.close();
|
||||
});
|
||||
fallback?.image.close();
|
||||
return canvas.transferToImageBitmap();
|
||||
}
|
||||
|
||||
@@ -582,6 +683,9 @@ export const OPEN_SATELLITE_FALLBACK_PROTOCOL = 'opensat-fallback';
|
||||
export const openSatelliteFallbackAttribution =
|
||||
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>';
|
||||
|
||||
const fallbackUrl = (maptilerKey: string) =>
|
||||
xyz(`https://api.maptiler.com/tiles/satellite-v2/{z}/{x}/{y}.jpg?key=${maptilerKey}`);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -606,8 +710,7 @@ export async function loadFallbackTile(
|
||||
signal: AbortSignal
|
||||
): Promise<ArrayBuffer | ImageBitmap> {
|
||||
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 });
|
||||
const response = await fetch(fallbackUrl(maptilerKey)(z, x, y), { signal });
|
||||
if (!response.ok) throw new Error(`No imagery for tile ${z}/${x}/${y}: ${response.status}`);
|
||||
return await response.arrayBuffer();
|
||||
}
|
||||
@@ -621,7 +724,7 @@ function tileOf(url: string) {
|
||||
export function registerOpenSatelliteProtocol(maptilerKey: string) {
|
||||
maplibregl.addProtocol(OPEN_SATELLITE_PROTOCOL, async (params, abortController) => {
|
||||
const [z, x, y] = tileOf(params.url);
|
||||
return { data: await loadTile(z, x, y, abortController.signal) };
|
||||
return { data: await loadTile(z, x, y, maptilerKey, abortController.signal) };
|
||||
});
|
||||
maplibregl.addProtocol(OPEN_SATELLITE_FALLBACK_PROTOCOL, async (params, abortController) => {
|
||||
const [z, x, y] = tileOf(params.url);
|
||||
|
||||
Reference in new issue
Block a user