Display HTML labels in the 3D scene.

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
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
Cast shadow
Receive shadow
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
Enabled
Mode
Hillshade
Hillshade intensity
Z factor
Hillshade zenith
Hillshade 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
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)
Feature count
Identifier
Memory usage (CPU)
Memory usage (GPU)
Name
Source CRS
Status
Resolution factor
Visible
Frozen
Interpretation
Loaded images
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
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
0% © IGN

Labels are HTML elements produced by Three.js' CSS2DRenderer. They can be styled using normal CSS styling.

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

import { MathUtils, Vector2, Vector3 } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";
import { CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.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 VectorSource from "@giro3d/giro3d/sources/VectorSource.js";
import TiledImageSource from "@giro3d/giro3d/sources/TiledImageSource.js";

// This example is based on planar_vector example, adding labels on features.
// You can directly jump to `geoJsonLayer.source.addEventListener('featuresloadend', ...)`,
// as the rest is similar.

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: extent.crs,
});

const map = new Map({ extent });
instance.add(map);

const controls = new MapControls(instance.view.camera, instance.domElement);
controls.target = extent.centerAsVector3();
controls.saveState();

controls.enableDamping = true;
controls.dampingFactor = 0.2;
controls.maxPolarAngle = Math.PI / 2.3;

instance.view.setControls(controls);

// Function to look at an extent from top
function lookTopDownAt(lookAtExtent, lookAtAltitude = 0) {
  const camera = instance.view.camera;

  const fov = camera.fov;

  const aspect = camera.aspect;

  const hFov = MathUtils.degToRad(fov) / 2;

  const dims = lookAtExtent.dimensions();

  const altitude = (Math.max(dims.x / aspect, dims.y) / Math.tan(hFov)) * 0.5;
  const position = lookAtExtent
    .centerAsVector3()
    .add(new Vector3(0, 0, altitude));
  const lookAt = lookAtExtent.centerAsVector3();

  lookAt.z = lookAtAltitude;

  // place camera above
  camera.position.copy(position);

  // look down
  camera.lookAt(lookAt);

  // make sure the camera isn't rotating around its view axis
  camera.rotation.z = 0;
  camera.rotation.x = 0.01; // quickfix to avoid bizarre jumps

  controls.target.copy(lookAt);
  controls.saveState();

  instance.notifyChange(camera);
}

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

const colorLayer = new ColorLayer({
  name: "wms_imagery",
  extent,
  source: wmsSource,
});
map.addLayer(colorLayer);

const style = new Style({
  fill: new Fill({
    color: "rgba(255, 165, 0, 0.2)",
  }),
  stroke: new Stroke({
    color: "white",
    width: 2,
  }),
});

const geojsonSource = new VectorSource({
  data: {
    url: "https://raw.githubusercontent.com/iTowns/iTowns2-sample-data/master/lyon.geojson",
    format: new GeoJSON(),
  },
  style,
});

const geoJsonLayer = new ColorLayer({
  name: "geojson",
  extent,
  source: geojsonSource,
});

map.addLayer(geoJsonLayer).then(() => {
  // Traverse the OpenLayers features that were added
  for (const feature of geojsonSource.getFeatures()) {
    // Create a label for each feature

    const text = document.createElement("div");
    // Virtually any inner markup is supported, here we're just inserting text
    text.innerText = feature.get("nom");
    text.title = `${feature.get("numero_arrondissement")}e arrondissement`;

    // Any CSS style is supported
    text.style.color = "#ffffff";
    text.style.padding = "0.2em 1em";
    text.style.maxWidth = "200px";
    text.style.border = "2px solid #cccccc";
    text.style.backgroundColor = "#080808";
    text.style.textAlign = "center";
    text.style.opacity = "80%";

    // Adding the label requires a Vector3 position, let's compute that
    // We'll position the label at the center of the geometry extent
    const olExtent = feature.getGeometry().getExtent();
    const giro3dExtent = new Extent(
      "EPSG:3946",
      olExtent[0],
      olExtent[2],
      olExtent[1],
      olExtent[3],
    );
    if (!giro3dExtent.isInside(extent)) {
      // The extent of the feature is not fully inside the map extent,
      // let's crop it to make sure the label will be inside the map
      giro3dExtent.intersect(extent);
    }
    const position = new Vector2();
    giro3dExtent.centerAsVector2(position);

    // Create our label and position it
    const label = new CSS2DObject(text);
    label.position.set(position.x, position.y, 0);
    label.updateMatrixWorld();
    // Give it a name so it shows up nicely in the inspector
    label.name = `${feature.get("nom")}`;
    // Simply add it to our instance
    // (we could also create a dedicated THREE.Group to have all the labels inside)
    instance.add(label);

    // By default, labels don't have mouse interaction enabled (pointerEvents = 'none')
    // Let's change that so we can click on it to zoom on it
    text.style.cursor = "pointer";
    text.style.pointerEvents = "auto";
    // Controls can interfer with the click event
    // e.g. this click event is triggered when we drag the map and the dragging ends on a label
    // but the mouseover is not, so use that to know if the user really wants to click
    // on the label.
    text.addEventListener("mouseover", () => {
      text.setAttribute("giro3d_over", "on");
    });
    text.addEventListener("mouseout", () => {
      text.removeAttribute("giro3d_over");
    });
    text.addEventListener("click", () => {
      if (text.getAttribute("giro3d_over")) {
        lookTopDownAt(giro3dExtent);
      }
    });
  }
  instance.notifyChange(geoJsonLayer);
});

instance.view.camera.position.set(extent.west, extent.south, 2000);

Inspector.attach("inspector", instance);
index.html
<!doctype html>
<html lang="en">
  <head>
    <title>HTML labels</title>
    <meta charset="UTF-8" />
    <meta name="name" content="htmllabels" />
    <meta name="description" content="Display HTML labels in the 3D scene." />
    <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>

    <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": "htmllabels",
    "dependencies": {
        "@giro3d/giro3d": "0.42.3"
    },
    "devDependencies": {
        "vite": "^3.2.3"
    },
    "scripts": {
        "start": "vite",
        "build": "vite build"
    }
}