Rendering a COG tile pyramid as layer group.
Data from a Cloud Optimized GeoTIFF (COG) tile pyramid can be rendered as a set of layers. In this example, a pyramid of 3-band GeoTIFFs is used to render RGB data. For each tile of the pyramid, a separate layer is created on demand. The lowest resolution layer serves as preview while higher resolutions are loading.
import 'ol/ol.css';
import GeoTIFF from 'ol/source/GeoTIFF';
import LayerGroup from 'ol/layer/Group';
import Map from 'ol/Map';
import TileGrid from 'ol/tilegrid/TileGrid';
import View from 'ol/View';
import WebGLTileLayer from 'ol/layer/WebGLTile';
import {getIntersection} from 'ol/extent';
// Metadata from https://s2downloads.eox.at/demo/EOxCloudless/2019/rgb/2019_EOxCloudless_rgb.json
// Tile grid of the GeoTIFF pyramid layout
const tileGrid = new TileGrid({
origin: [-180, 90],
resolutions: [0.703125, 0.3515625, 0.17578125, 8.7890625e-2, 4.39453125e-2],
tileSizes: [
[512, 256],
[1024, 512],
[2048, 1024],
[4096, 2048],
[4096, 4096],
],
});
const pyramid = new LayerGroup();
const layerForUrl = {};
const zs = tileGrid.getResolutions().length;
function useLayer(z, x, y) {
const url = `https://s2downloads.eox.at/demo/EOxCloudless/2019/rgb/${z}/${y}/${x}.tif`;
if (!(url in layerForUrl)) {
pyramid.getLayers().push(
new WebGLTileLayer({
minZoom: z,
maxZoom: z === 0 || z === zs - 1 ? undefined : z + 1,
extent: tileGrid.getTileCoordExtent([z, x, y]),
source: new GeoTIFF({
sources: [
{
url: url,
},
],
}),
})
);
layerForUrl[url] = true;
}
}
const map = new Map({
target: 'map',
layers: [pyramid],
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 0,
showFullExtent: true,
}),
});
// Add overview layer
useLayer(0, 0, 0);
// Add layer for specific extent on demand
map.on('moveend', () => {
const view = map.getView();
tileGrid.forEachTileCoord(
getIntersection([-180, -90, 180, 90], view.calculateExtent()),
tileGrid.getZForResolution(view.getResolution()),
([z, x, y]) => useLayer(z, x, y)
);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GeoTIFF tile pyramid</title>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<script src="https://unpkg.com/elm-pep"></script>
<!-- The lines below are only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,TextDecoder"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.18.3/minified.js"></script>
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<script src="main.js"></script>
</body>
</html>
{
"name": "cog-pyramid",
"dependencies": {
"ol": "6.12.0"
},
"devDependencies": {
"parcel": "^2.0.0"
},
"scripts": {
"start": "parcel index.html",
"build": "parcel build --public-url . index.html"
}
}