Limit the display of a color layer or a map within an elevation range.

Per-map range
Per-layer range (color layer only)
100% © Mapbox

By passing the elevationRange option to the ColorLayer and/or Map constructor, you can limit the visibility of this layer/map within this range. A possible use case is to limit the display of a satellite layer above the sea level, then limit the display of a bathymetry dataset below the sea level.

index.js
import colormap from "colormap";

import XYZ from "ol/source/XYZ.js";

import { Color, Vector3 } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";

import Extent from "@giro3d/giro3d/core/geographic/Extent.js";
import Instance from "@giro3d/giro3d/core/Instance.js";
import ColorLayer from "@giro3d/giro3d/core/layer/ColorLayer.js";
import TiledImageSource from "@giro3d/giro3d/sources/TiledImageSource.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 ColorMap from "@giro3d/giro3d/core/layer/ColorMap.js";
import MapboxTerrainFormat from "@giro3d/giro3d/formats/MapboxTerrainFormat.js";

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

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

  const setValue = (v) => {
    element.valueAsNumber = v;
    onChange(element.valueAsNumber);
  };

  const initialValue = element.valueAsNumber;

  return [setValue, initialValue, element];
}

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;

  // eslint-disable-next-line no-undef
  const values = colormap({ colormap: preset, nshades });
  // eslint-disable-next-line no-undef
  const colors = values.map((v) => new Color(v));

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

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

  return colors;
}

const center = { x: -13601505, y: 5812315 };

const extent = Extent.fromCenterAndSize("EPSG:3857", center, 20000, 20000);

const instance = new Instance({
  target: "view",
  crs: extent.crs,
  backgroundColor: null,
});

const map = new Map({
  extent,
  elevationRange: { min: 500, max: 3000 },
});

instance.add(map);

const colorRamp = makeColorRamp("viridis");

const key =
  "pk.eyJ1IjoidG11Z3VldCIsImEiOiJjbGJ4dTNkOW0wYWx4M25ybWZ5YnpicHV6In0.KhDJ7W5N3d1z3ArrsDjX_A";
// Adds a XYZ elevation layer with MapBox terrain RGB tileset
const elevationLayer = new ElevationLayer({
  name: "xyz_elevation",
  extent,
  source: new TiledImageSource({
    format: new MapboxTerrainFormat(),
    source: new XYZ({
      url: `https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=${key}`,
      projection: extent.crs,
      crossOrigin: "anonymous",
    }),
  }),
  colorMap: new ColorMap(colorRamp, 700, 2500),
});
map.addLayer(elevationLayer);

// Adds a XYZ color layer with MapBox satellite tileset
const colorLayer = new ColorLayer({
  name: "xyz_color",
  extent,
  source: new TiledImageSource({
    source: new XYZ({
      url: `https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.webp?access_token=${key}`,
      projection: extent.crs,
      crossOrigin: "anonymous",
    }),
  }),
  elevationRange: { min: 500, max: 3000 },
});
map.addLayer(colorLayer);

// Sets the camera position
instance.view.camera.position.set(-13615016, 5835706, 14797);

const controls = new MapControls(instance.view.camera, instance.domElement);
controls.target = new Vector3(-13603869, 5814829, 0);
controls.saveState();
controls.enableDamping = true;
controls.dampingFactor = 0.2;
controls.maxPolarAngle = Math.PI / 2.3;
instance.view.setControls(controls);

Inspector.attach("inspector", instance);

let colorLayerRange = colorLayer.elevationRange;

bindToggle("toggle-colorlayer-range", (enabled) => {
  if (enabled) {
    colorLayer.elevationRange = colorLayerRange;
  } else {
    colorLayer.elevationRange = null;
  }

  document.getElementById("layerMin").disabled = !enabled;

  document.getElementById("layerMax").disabled = !enabled;

  instance.notifyChange(map);
});

bindSlider("mapMin", (v) => {
  map.elevationRange.min = v;
  instance.notifyChange(map);
});
bindSlider("mapMax", (v) => {
  map.elevationRange.max = v;
  instance.notifyChange(map);
});
bindSlider("layerMin", (v) => {
  colorLayer.elevationRange = { min: v, max: colorLayer.elevationRange.max };
  colorLayerRange = colorLayer.elevationRange;
  instance.notifyChange(map);
});
bindSlider("layerMax", (v) => {
  colorLayer.elevationRange = { min: colorLayer.elevationRange.min, max: v };
  colorLayerRange = colorLayer.elevationRange;
  instance.notifyChange(map);
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>Elevation ranges</title>
    <meta charset="UTF-8" />
    <meta name="name" content="elevation_ranges" />
    <meta
      name="description"
      content="Limit the display of a color layer or a map within an elevation range."
    />
    <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/next/css/example.css"
    />

    <style>
      #view canvas {
        background-image: linear-gradient(45deg, #aaaaaa 25%, transparent 25%),
          linear-gradient(-45deg, #aaaaaa 25%, transparent 25%),
          linear-gradient(45deg, transparent 75%, #aaaaaa 75%),
          linear-gradient(-45deg, transparent 75%, #aaaaaa 75%);
        background-size: 20px 20px;
        background-position:
          0 0,
          0 10px,
          10px -10px,
          -10px 0px;
      }
    </style>
  </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="mh-100 overflow-y-auto">
        <div class="card mb-1">
          <div class="card-header">Per-map range</div>
          <fieldset class="container card-body" id="options">
            <label for="mapMin" class="form-label">Lower bound</label>
            <div class="input-group">
              <input
                type="range"
                min="500"
                max="3000"
                value="500"
                class="form-range"
                id="mapMin"
                autocomplete="off"
              />
            </div>

            <div class="my-2"></div>

            <label for="mapMax" class="form-label">Upper bound</label>
            <div class="input-group">
              <input
                type="range"
                min="500"
                max="3000"
                value="3000"
                class="form-range"
                id="mapMax"
                autocomplete="off"
              />
            </div>
          </fieldset>
        </div>

        <div class="card mb-1">
          <div class="card-header">Per-layer range (color layer only)</div>
          <fieldset class="container card-body" id="options">
            <!-- Toggle elevation range feature -->
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                type="checkbox"
                checked="true"
                role="switch"
                id="toggle-colorlayer-range"
                autocomplete="off"
              />
              <label class="form-check-label" for="toggle-colorlayer-range"
                >Enable elevation range</label
              >
            </div>

            <label for="layerMin" class="form-label">Lower bound</label>
            <div class="input-group">
              <input
                type="range"
                min="500"
                max="3000"
                value="500"
                class="form-range"
                id="layerMin"
                autocomplete="off"
              />
            </div>

            <div class="my-2"></div>

            <label for="layerMax" class="form-label">Upper bound</label>
            <div class="input-group">
              <input
                type="range"
                min="500"
                max="3000"
                value="3000"
                class="form-range"
                id="layerMax"
                autocomplete="off"
              />
            </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": "elevation_ranges",
    "dependencies": {
        "colormap": "^2.3.2",
        "@giro3d/giro3d": "git+https://gitlab.com/giro3d/giro3d.git"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}