Button to toggle layers on/off

Hello, I am completely new to Cesium and just starting to explore the software a bit more. I have tried creating Cesium stories but would like some more functionality from my map. Currently I am trying to create buttons to toggle layers on/off. I tried this code, which tries to create a button to toggle the “ports” layer on/off. It should hide the ports layer by default when opening the map. However, this does not work, and when clicking the button I get an error, which I have pasted below. Please let me know if you know where I am going wrong in this code.

An error occurred while rendering. Rendering has stopped.
TypeError: Cannot read property ‘length’ of undefined
TypeError: Cannot read property ‘length’ of undefined
at DataSourceDisplay.update (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:226497:29)
at Viewer._onTick (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:329502:45)
at Event.raiseEvent (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:14139:22)
at Clock.tick (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:51089:17)
at CesiumWidget.render (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:323161:37)
at render (https://sandcastle.cesium.com/CesiumUnminified/Cesium.js:322411:20)

Here is a link to my code: Sandcastle code link

You need to set the value of ports in the then from the load.

Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0MTZmZjE1YS0yZTNiLTRjNmMtOWRiNC05MmYxN2Q2NjQ1ODciLCJpZCI6NTk1NDEsImlhdCI6MTYyNDI3NzE3MX0.ef_zZ5afWOxmFAnawKf4erhCfW8-4GWb3gdc95bTJSU";

var viewer = new Cesium.Viewer("cesiumContainer");

var ports;

Cesium.IonResource.fromAssetId(546046)
  .then(function (resource) {
    return Cesium.KmlDataSource.load(resource, {
      camera: viewer.scene.camera,
      canvas: viewer.scene.canvas,
    });
  })
  .then(function (dataSource) {
    ports = dataSource;
    return viewer.dataSources.add(dataSource);
  })
  .then(function (dataSource) {

The only other thing I see is that the state of the checkbox is not correct.

Scott

2 Likes

That worked well, thank you

1 Like

@scottUFR

Thank you for posting - your solution looks perfect :rocket:

-Sam