Retrieve the pixel value of a layer at given coordinates.

Parameters
100% layers from © IGN

Use the getPixel() method to change the mouse pointer when hovering a non-transparent pixel on the map.

index.js
import { get as getProjection } from "ol/proj.js";
import { TileWMS } from "ol/source.js";
import { Vector2, Vector3 } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";

import Coordinates from "@giro3d/giro3d/core/geographic/Coordinates.js";
import CoordinateSystem from "@giro3d/giro3d/core/geographic/CoordinateSystem.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 Map from "@giro3d/giro3d/entities/Map.js";
import Inspector from "@giro3d/giro3d/gui/Inspector.js";
import TiledImageSource from "@giro3d/giro3d/sources/TiledImageSource.js";
import WmtsSource from "@giro3d/giro3d/sources/WmtsSource.js";

function bindColorPicker(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() {
    // Let's change the classification color with the color picker value
    const hexColor = element.value;
    onChange(new Color(hexColor));
  };

  const externalFunction = (v) => {
    element.value = `#${new Color(v).getHexString()}`;
    onChange(element.value);
  };

  return [externalFunction, new Color(element.value), element];
}

const extent = new Extent(
  CoordinateSystem.epsg3857,
  -20037508.342789244,
  20037508.342789244,
  -20048966.1,
  20048966.1,
);

const instance = new Instance({
  target: "view",
  crs: extent.crs,
  backgroundColor: "black",
});
const camPos = new Vector3(258767.3, 6247882.8, 6872.5);
instance.view.camera.position.set(camPos.x, camPos.y, camPos.z);

const controls = new MapControls(instance.view.camera, instance.domElement);
instance.view.setControls(controls);

controls.target.set(camPos.x, camPos.y + 1, 0);

const map = new Map({
  extent,
  backgroundColor: "gray",
  maxSubdivisionLevel: 19,
  lighting: {
    enabled: true,
    zFactor: 8,
  },
  terrain: false,
});
instance.add(map);

const capabilitiesUrl =
  "https://data.geopf.fr/wmts?SERVICE=WMTS&VERSION=1.0.0&REQUEST=GetCapabilities";

const wmsLayer = new ColorLayer({
  name: "museums",
  source: new TiledImageSource({
    httpTimeout: 10000,
    source: new TileWMS({
      url: "https://data.geopf.fr/wms-v/wms?SERVICE=WMS&VERSION=1.3.0",
      params: { LAYERS: "POI.MUSEUM", TILED: true },
      crossOrigin: "anonymous",
      projection: getProjection("EPSG:3857"),
    }),
  }),
});

async function initializeWmts() {
  const orthophotoWmts = await WmtsSource.fromCapabilities(capabilitiesUrl, {
    layer: "HR.ORTHOIMAGERY.ORTHOPHOTOS",
  });

  const layer = new ColorLayer({
    name: "orthophotos",
    extent: map.extent,
    source: orthophotoWmts,
  });
  layer.userData.zOrder = 0;

  await Promise.all([map.addLayer(layer), map.addLayer(wmsLayer)]);

  const [setColor, _, colorPicker] = bindColorPicker("color", () => {});

  instance.domElement.addEventListener("pointermove", (event) => {
    const canvasCoords = instance.eventToCanvasCoords(event, new Vector2());

    const results = map.pick(canvasCoords);

    if (results && results.length > 0) {
      const point = results[0].point;
      const coordinates = new Coordinates(
        instance.coordinateSystem,
        point.x,
        point.y,
      );

      const hit = wmsLayer.getPixel({ coordinates, size: 10 });

      if (hit && hit.length > 0) {
        setColor(hit[0]);
      }

      colorPicker.style.display = hit ? "block" : "none";
      instance.domElement.style.cursor = hit ? "pointer" : "";
    } else {
      colorPicker.style.display = "none";
      instance.domElement.style.cursor = "";
    }
  });
}

Inspector.attach("inspector", instance);

initializeWmts();
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>Sample layer color</title>
    <meta charset="UTF-8" />
    <meta name="name" content="layer-get-pixel" />
    <meta
      name="description"
      content="Retrieve the pixel value of a layer at given coordinates."
    />
    <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" style="width: 10rem">
      <div class="card">
        <div class="card-header">Parameters</div>
        <div class="card-body">
          <!-- Color -->
          <label class="form-check-label w-100 mb-2" for="color"
            >Picked color</label
          >
          <input
            disabled
            type="color"
            class="form-control form-control-color float-end w-100"
            id="color"
            value="#ffffff"
            title="color"
            autocomplete="off"
          />
        </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": "layer-get-pixel",
    "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',
    },
  },
})