Create a mosaic of SRTM tiles.

Parameters
100% © NASA,

The AggregateImageSource can combine multiple ImageSources into one. One the many benefits of this approach is that is reduces the number of layers in a map, which helps improve performance. It also makes it possible to have more than one elevation source on a map, which only supports a single elevation layer.

index.js
import { Feature } from "ol";
import { fromExtent } from "ol/geom/Polygon.js";
import { Stroke, Style } from "ol/style.js";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";

import ColorMap from "@giro3d/giro3d/core/ColorMap.js";
import CoordinateSystem from "@giro3d/giro3d/core/geographic/CoordinateSystem.js";
import Instance from "@giro3d/giro3d/core/Instance.js";
import ColorLayer from "@giro3d/giro3d/core/layer/ColorLayer.js";
import ElevationLayer from "@giro3d/giro3d/core/layer/ElevationLayer.js";
import Map from "@giro3d/giro3d/entities/Map.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
import AggregateImageSource from "@giro3d/giro3d/sources/AggregateImageSource.js";
import GeoTIFFSource from "@giro3d/giro3d/sources/GeoTIFFSource.js";
import VectorSource from "@giro3d/giro3d/sources/VectorSource.js";
import OpenLayersUtils from "@giro3d/giro3d/utils/OpenLayersUtils.js";

function bindToggle(id, onChange) {
  const element = document.getElementById(id);
  if (!(element instanceof HTMLInputElement)) {
    throw new Error(
      "invalid binding element: expected HTMLButtonElement, got: " +
        element.constructor.name,
    );
  }

  element.oninput = function oninput() {
    onChange(element.checked);
  };

  const callback = (v) => {
    element.checked = v;
    onChange(element.checked);
  };

  return [callback, element.checked, element];
}

function makeColorRamp(
  preset,
  discrete = false,
  invert = false,
  mirror = false,
) {
  let nshades = discrete ? 10 : 256;

  const values = colormap({ colormap: preset, nshades });

  const colors = values.map((v) => new Color(v));

  if (invert) {
    colors.reverse();
  }

  if (mirror) {
    const mirrored = [...colors, ...colors.reverse()];
    return mirrored;
  }

  return colors;
}

const CRS = CoordinateSystem.epsg3857;

const instance = new Instance({
  target: "view",
  crs: CRS,
});

async function loadData() {
  const baseUrl = "https://3d.oslandia.com/giro3d/rasters/";
  const tiles = [
    "N41E008.hgt.tif",
    "N41E009.hgt.tif",
    "N42E008.hgt.tif",
    "N42E009.hgt.tif",
  ];

  // Create one GeoTIFFSource per SRTM tile
  // Note that SRTM tiles are in EPSG:4326, so they will be reprojected
  // to EPSG:3857 which is the CRS of the instance.
  const sources = tiles.map(
    (tile) =>
      new GeoTIFFSource({
        url: baseUrl + tile,
        crs: CoordinateSystem.epsg4326,
      }),
  );

  // Then combine them in an aggregate source.
  // Note: all sub-sources must have the same CRS.
  const aggregateSource = new AggregateImageSource({ sources });

  // Let's initialize the source to be able to retrieve its extent
  await aggregateSource.initialize({ targetProjection: CRS });

  const extent = aggregateSource.getExtent().as(CRS);

  const map = new Map({
    extent,
    backgroundColor: "gray",
    lighting: true,
  });

  instance.add(map).catch(console.error);

  const min = 0;
  const max = 2700;

  const layer = new ElevationLayer({
    minmax: { min, max },
    colorMap: new ColorMap({ colors: makeColorRamp("earth"), min, max }),
    source: aggregateSource,
  });

  await map.addLayer(layer);

  // Let's now create a vector layer to visualize the extents of the SRTM tiles.
  const tileOutlines = sources.map((source) => {
    const olExtent = OpenLayersUtils.toOLExtent(source.getExtent());
    const olPolygon = fromExtent(olExtent);
    const feature = new Feature(olPolygon);
    return feature;
  });

  const vectorLayer = new ColorLayer({
    source: new VectorSource({
      data: tileOutlines,
      dataProjection: CoordinateSystem.epsg4326,
      style: new Style({
        stroke: new Stroke({
          width: 4,
          color: "red",
        }),
      }),
    }),
  });

  await map.addLayer(vectorLayer);

  const center = extent.centerAsVector2();
  instance.view.camera.position.set(center.x, center.y, 500_000);

  const controls = new MapControls(instance.view.camera, instance.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.2;
  controls.target.set(center.x, center.y + 1, 0);
  instance.view.setControls(controls);

  // Attach the inspector
  Inspector.attach("inspector", instance);

  bindToggle("show-tile-extents", (show) => {
    vectorLayer.visible = show;
    instance.notifyChange(vectorLayer);
  });
}

loadData().catch(console.error);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>SRTM Tiles</title>
    <meta charset="UTF-8" />
    <meta name="name" content="srtm-tiles" />
    <meta name="description" content="Create a mosaic of SRTM tiles." />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="icon" href="https://giro3d.org/images/favicon.svg" />
    <link
      href="https://giro3d.org/assets/bootstrap-custom.css"
      rel="stylesheet"
    />
    <script src="https://giro3d.org/assets/bootstrap.bundle.min.js"></script>
    <link
      rel="stylesheet"
      type="text/css"
      href="https://giro3d.org/latest/examples/css/example.css"
    />
  </head>

  <body>
    <div id="view" class="m-0 p-0 w-100 h-100"></div>
    <div
      id="inspector"
      class="position-absolute top-0 start-0 mh-100 overflow-auto"
    ></div>

    <div class="side-pane-with-status-bar">
      <div class="card">
        <div class="card-header">Parameters</div>
        <div class="card-body">
          <fieldset id="options">
            <!-- Show extents -->
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                type="checkbox"
                checked="true"
                role="switch"
                id="show-tile-extents"
                autocomplete="off"
              />
              <label class="form-check-label" for="show-tile-extents"
                >Show tile extents</label
              >
            </div>
          </fieldset>
        </div>
      </div>
    </div>

    <script type="module" src="index.js"></script>
    <script>
      /* activate popovers */
      const popoverTriggerList = [].slice.call(
        document.querySelectorAll('[data-bs-toggle="popover"]'),
      );
      popoverTriggerList.map(
        // bootstrap is used as script in the template, disable warning about undef
        // eslint-disable-next-line no-undef
        (popoverTriggerEl) =>
          new bootstrap.Popover(popoverTriggerEl, {
            trigger: "hover",
            placement: "left",
            content: document.getElementById(
              popoverTriggerEl.getAttribute("data-bs-content"),
            ).innerHTML,
            html: true,
          }),
      );
    </script>
  </body>
</html>
package.json
{
    "name": "srtm-tiles",
    "dependencies": {
        "@giro3d/giro3d": "1.0.0"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}
vite.config.js
import { defineConfig } from "vite";

export default defineConfig({
  build: {
    target: 'esnext',
  },
  optimizeDeps: {
    esbuildOptions: {
      target: 'esnext',
    },
  },
})