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

Giro3D version
THREE.js version
OpenLayers version
CRS
Memory usage (CPU)
Memory usage (GPU)
Frames
Clear color
Clear alpha
Status
Local clipping enabled
Capabilities
WebGL 2
Max texture units
Max texture size
Precision
Max fragment shader uniforms
Logarithmic depth buffer
Max shader attributes
Check shader errors
EXT_clip_control
EXT_color_buffer_float
EXT_color_buffer_half_float
EXT_conservative_depth
EXT_depth_clamp
EXT_float_blend
EXT_polygon_offset_clamp
EXT_texture_compression_bptc
EXT_texture_compression_rgtc
EXT_texture_filter_anisotropic
EXT_texture_mirror_clamp_to_edge
EXT_texture_norm16
NV_shader_noperspective_interpolation
OES_draw_buffers_indexed
OES_sample_variables
OES_shader_multisample_interpolation
OES_texture_float_linear
OVR_multiview2
WEBGL_clip_cull_distance
WEBGL_compressed_texture_astc
WEBGL_compressed_texture_etc
WEBGL_compressed_texture_etc1
WEBGL_compressed_texture_s3tc
WEBGL_compressed_texture_s3tc_srgb
WEBGL_debug_renderer_info
WEBGL_debug_shaders
WEBGL_lose_context
WEBGL_multi_draw
WEBGL_polygon_mode
WEBGL_stencil_texturing
MSAA
EDL
EDL Radius
EDL Strength
Inpainting
Inpainting steps
Inpainting depth contrib.
Point cloud occlusion
Type
FOV
Automatic plane computation
Far plane
Near plane
Max far plane
Min near plane
Width (pixels)
Height (pixels)
x
y
z
x
y
z
color
Enable cache
Default TTL (seconds)
Capacity (MB)
Capacity (entries)
Entries
Memory usage (approx)
Pending requests
Running requests
Completed requests
Memory tracker
Identifier
Memory usage (CPU)
Memory usage (GPU)
Status
Render order
Enable
Plane normal X
Plane normal Y
Plane normal Z
Distance
Helper size
Negate plane
Visible
Freeze updates
Opacity
Show volumes
Volume color
Discard no-data values
Sidedness
Front
Depth test
Visible tiles
Reachable tiles
Loaded tiles
Elevation range minimum
Elevation range maximum
Tile width (pixels)
Tile height (pixels)
Show grid
Background
Background opacity
Show tiles outlines
Tile outline color
Show tile info
Show extent
Extent color
Subdivision threshold
Deformation
Wireframe
Tile subdivisions
Show collider meshes
CPU terrain
Stitching
Geometry pool
Enable
Intensity
Z-factor
Sun zenith
Sun azimuth
Elevation layers only
Enable
Color
Opacity
X step
Y step
X Offset
Y Offset
Thickness
Enable
Color
Thickness
Opacity
Primary interval (m)
Secondary interval (m)
Brightness
Contrast
Saturation
Layer count
Render state
Normal
Layers
Identifier
Memory usage (CPU)
Memory usage (GPU)
Name
Source CRS
Status
Resolution factor
Visible
Frozen
Interpretation
Loaded images
Elevation range minimum
Elevation range maximum
Blending mode
Normal
Brightness
Contrast
Saturation
Opacity
Show extent
Extent color
Enabled
Mode
Elevation
Lower bound
Upper bound
Type
Color space
Data type
Flip Y
Synchronous
CRS
Memory usage (CPU)
Memory usage (GPU)
Loaded/Requested
CRS
Zoom levels
Main URL
Inner source
Identifier
Memory usage (CPU)
Memory usage (GPU)
Name
Source CRS
Status
Resolution factor
Visible
Frozen
Interpretation
Loaded images
Minimum elevation
Maximum elevation
Show extent
Extent color
Enabled
Mode
Elevation
Lower bound
Upper bound
Type
Color space
Data type
Flip Y
Synchronous
CRS
Memory usage (CPU)
Memory usage (GPU)
Loaded/Requested
CRS
Zoom levels
Main URL
Inner source
Show helpers
Show hidden objects
Name filter
Hierarchy
Properties
isObject3D
uuid
name
type
matrixAutoUpdate
matrixWorldAutoUpdate
matrixWorldNeedsUpdate
visible
castShadow
receiveShadow
frustumCulled
renderOrder
x
y
z
x
y
z
Per-map range
Per-layer range (color layer only)
0% © 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, min, max, step) => {
    if (min != null && max != null) {
      element.min = min.toString();
      element.max = max.toString();

      if (step != null) {
        element.step = step;
      }
    }
    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;

  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 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/latest/examples/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": "0.41.0"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}