Illustrates how transparency in maps work.

100% © IGN, © iTowns

Transparency in maps (and any other 3D object) is a tricky problem. Due to limitations in how 3D renderers work, it is not generally possible to correctly display overlapping transparent objects. For example, set the opacity of at least 2 maps to less than 100%, rotate the camera around, and observe various rendering issues, such as missing map tiles.

index.js
import colormap from "colormap";

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

import { Fill, Stroke, Style } from "ol/style.js";
import TileWMS from "ol/source/TileWMS.js";
import GeoJSON from "ol/format/GeoJSON.js";

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

Instance.registerCRS(
  "EPSG:3946",
  "+proj=lcc +lat_1=45.25 +lat_2=46.75 +lat_0=46 +lon_0=3 +x_0=1700000 +y_0=5200000 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs",
);

const extent = new Extent(
  "EPSG:3946",
  1837816.94334,
  1847692.32501,
  5170036.4587,
  5178412.82698,
);

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

const terrainMap = new Map({ extent, side: DoubleSide, hillshading: true });
instance.add(terrainMap);

const min = 100;
const max = 300;

const values = colormap({ colormap: "viridis", nshades: 256 });
const colors = values.map((v) => new Color(v));
const colorMap = new ColorMap(colors, min, max);

const elevationLayer = new ElevationLayer({
  name: "terrain",
  extent,
  colorMap,
  minmax: { min, max },
  source: new TiledImageSource({
    source: new TileWMS({
      url: "https://data.geopf.fr/wms-r",
      projection: "EPSG:3946",
      crossOrigin: "anonymous",
      params: {
        LAYERS: ["ELEVATION.ELEVATIONGRIDCOVERAGE.HIGHRES"],
        FORMAT: "image/x-bil;bits=32",
      },
    }),
    format: new BilFormat(),
    noDataValue: -1000,
  }),
});

terrainMap.addLayer(elevationLayer);

const orthophotoMap = new Map({ extent, side: DoubleSide });
instance.add(orthophotoMap);

const orthophotoLayer = new ColorLayer({
  name: "orthophoto",
  extent,
  source: new TiledImageSource({
    source: new TileWMS({
      url: "https://data.geopf.fr/wms-r",
      projection: "EPSG:3946",
      params: {
        LAYERS: ["HR.ORTHOIMAGERY.ORTHOPHOTOS"],
        FORMAT: "image/jpeg",
      },
    }),
  }),
});
orthophotoMap.addLayer(orthophotoLayer);

const vectorMap = new Map({ extent, side: DoubleSide, backgroundOpacity: 0 });
instance.add(vectorMap);

const geoJsonLayer = new ColorLayer({
  name: "geojson",
  extent,
  source: new VectorSource({
    data: {
      url: "https://raw.githubusercontent.com/iTowns/iTowns2-sample-data/master/lyon.geojson",
      format: new GeoJSON(),
    },
    dataProjection: "EPSG:3946",
    style: new Style({
      fill: new Fill({
        color: "rgba(255, 165, 0, 0.6)",
      }),
      stroke: new Stroke({
        color: "white",
      }),
    }),
  }),
});

vectorMap.addLayer(geoJsonLayer);

orthophotoMap.object3d.translateZ(+1500);
orthophotoMap.object3d.updateMatrixWorld();
vectorMap.object3d.translateZ(+2500);
vectorMap.object3d.updateMatrixWorld();

instance.view.camera.position.set(1832816, 5163527, 6121);

const controls = new MapControls(instance.view.camera, instance.domElement);
controls.target = extent.centerAsVector3();
controls.saveState();
controls.enableDamping = true;
controls.dampingFactor = 0.2;
instance.view.setControls(controls);

Inspector.attach("inspector", instance);

bindToggle("show-terrain", (v) => {
  terrainMap.visible = v;
  instance.notifyChange();
});
bindToggle("show-orthophoto", (v) => {
  orthophotoMap.visible = v;
  instance.notifyChange();
});
bindToggle("show-vector", (v) => {
  vectorMap.visible = v;
  instance.notifyChange();
});

bindSlider("terrain-opacity", (o) => {
  terrainMap.opacity = o;
  instance.notifyChange();
});
bindSlider("orthophoto-opacity", (o) => {
  orthophotoMap.opacity = o;
  instance.notifyChange();
});
bindSlider("vector-opacity", (o) => {
  vectorMap.opacity = o;
  instance.notifyChange();
});
bindSlider("vector-bg-opacity", (o) => {
  vectorMap.backgroundOpacity = o;
  instance.notifyChange(vectorMap);
});
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>Stacking transparent maps</title>
    <meta charset="UTF-8" />
    <meta name="name" content="map_transparency_stack" />
    <meta
      name="description"
      content="Illustrates how transparency in maps work."
    />
    <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">
        <!-- Vector map -->
        <div class="card mb-1">
          <div class="card-header">
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                checked
                type="checkbox"
                role="switch"
                id="show-vector"
                autocomplete="off"
              />
              <label class="form-check-label" for="show-vector"
                >Vector map</label
              >
            </div>
          </div>

          <div class="card-body" id="vector-options">
            <!-- Opacity -->
            <label for="vector-opacity" class="form-label">Map opacity</label>
            <div class="input-group">
              <input
                type="range"
                min="0"
                step="0.01"
                max="1"
                value="1"
                class="form-range"
                id="vector-opacity"
                autocomplete="off"
              />
            </div>

            <!-- Opacity -->
            <label for="vector-bg-opacity" class="form-label"
              >Background opacity</label
            >
            <div class="input-group">
              <input
                type="range"
                min="0"
                step="0.01"
                max="1"
                value="0"
                class="form-range"
                id="vector-bg-opacity"
                autocomplete="off"
              />
            </div>
          </div>
        </div>

        <!-- Orthophoto map -->
        <div class="card mb-1">
          <div class="card-header">
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                checked
                type="checkbox"
                role="switch"
                id="show-orthophoto"
                autocomplete="off"
              />
              <label class="form-check-label" for="show-orthophoto"
                >Orthophoto map</label
              >
            </div>
          </div>

          <div class="card-body" id="orthophoto-options">
            <!-- Opacity -->
            <label for="orthophoto-opacity" class="form-label"
              >Map opacity</label
            >
            <div class="input-group">
              <input
                type="range"
                min="0"
                step="0.01"
                max="1"
                value="1"
                class="form-range"
                id="orthophoto-opacity"
                autocomplete="off"
              />
            </div>
          </div>
        </div>

        <!-- Terrain map -->
        <div class="card mb-1">
          <div class="card-header">
            <div class="form-check form-switch">
              <input
                class="form-check-input"
                checked
                type="checkbox"
                role="switch"
                id="show-terrain"
                autocomplete="off"
              />
              <label class="form-check-label" for="show-terrain"
                >Terrain map</label
              >
            </div>
          </div>

          <div class="card-body" id="terrain-options">
            <!-- Opacity -->
            <label for="terrain-opacity" class="form-label">Map opacity</label>
            <div class="input-group">
              <input
                type="range"
                min="0"
                step="0.01"
                max="1"
                value="1"
                class="form-range"
                id="terrain-opacity"
                autocomplete="off"
              />
            </div>
          </div>
        </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": "map_transparency_stack",
    "dependencies": {
        "colormap": "^2.3.2",
        "@giro3d/giro3d": "0.41.0"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}