Search code examples
javascriptlabelzoomingcesiumjs

Cesium: display / hide Labels depending on the Zoom level


I want to hide map's labels when the zoom is increased above a certain level.

For this example, I want to hide all labels related to the collection1, after the zoom level of 5: https://codepen.io/ollazarev/pen/XBWEEq

let viewer = new Cesium.Viewer('cesiumContainer', {
  animation: false,
  baseLayerPicker: false,
  fullscreenButton: false,
  geocoder: false,
  homeButton: false,
  infoBox: false,
  sceneModePicker: false,
  timeline: false,
  navigationHelpButton: false,
  navigationInstructionsInitiallyVisible: false,
});

let collection1 = new Cesium.LabelCollection();
collection1.add({
  position: Cesium.Cartesian3.fromDegrees(-101.678, 57.7833),
  text: 'Canada',
});
collection1.add({
  position : Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),
  text: 'Philadelphia',
});
viewer.scene.primitives.add(collection1);

let collection2 = new Cesium.LabelCollection();
collection2.add({
  position: Cesium.Cartesian3.fromDegrees(-74.0059728, 40.7127753),
  text: 'New York',
});
collection2.add({
  position : Cesium.Cartesian3.fromDegrees(-79.38318429999998, 43.653226),
  text: 'Toronto',
});
viewer.scene.primitives.add(collection2);

Solution

  • Cesium's 3D camera isn't aware of "zoom levels" as such, but you can turn off labels after a certain distance away using translucencyByDistance.

    For example, here's your demo again with translucencyByDistance added to each of the labels:

    let viewer = new Cesium.Viewer('cesiumContainer', {
      animation: false,
      baseLayerPicker: false,
      fullscreenButton: false,
      geocoder: false,
      homeButton: false,
      infoBox: false,
      sceneModePicker: false,
      timeline: false,
      navigationHelpButton: false,
      navigationInstructionsInitiallyVisible: false,
    });
    
    let collection1 = new Cesium.LabelCollection();
    collection1.add({
      position: Cesium.Cartesian3.fromDegrees(-101.678, 57.7833),
      text: 'Canada',
      translucencyByDistance : new Cesium.NearFarScalar(6.0e7, 1.0, 7.0e7, 0.0)
    });
    collection1.add({
      position : Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),
      text: 'Philadelphia',
      translucencyByDistance : new Cesium.NearFarScalar(4.0e7, 1.0, 7.0e7, 0.0)
    });
    viewer.scene.primitives.add(collection1);
    
    let collection2 = new Cesium.LabelCollection();
    collection2.add({
      position: Cesium.Cartesian3.fromDegrees(-74.0059728, 40.7127753),
      text: 'New York',
      translucencyByDistance : new Cesium.NearFarScalar(1.0e7, 1.0, 3.0e7, 0.0)
    });
    collection2.add({
      position : Cesium.Cartesian3.fromDegrees(-79.38318429999998, 43.653226),
      text: 'Toronto',
      translucencyByDistance : new Cesium.NearFarScalar(3.0e7, 1.0, 5.0e7, 0.0)
    });
    viewer.scene.primitives.add(collection2);