从 Cesium Display 加载和卸载 GeoJSON

Load and unload GeoJSON from Cesium Display

我有一个 Cesiumjs 显示器,我有一个复选框 (class .checkbox),我想控制一个项目在地图上的显示。 :

        var loadedGeometries = {};

        // We want to load/unload geometries when clicking on the checkboxes
        $('.checkbox').on('click', function (event) {
            var geometryID = id; // some unique database ID for the object to be displayed
            if ($(this).prop('checked')) {
                // it's checked, load it onto the map
                $.get('/geometry/' + geometryID, function (data) {
                    var myDataSource = Cesium.GeoJsonDataSource.load(data['points'], {
                        markerSize: 24,
                        markerColor: Cesium.Color.RED,
                        markerSymbol: 't'
                    }); // data['points'] is GeoJSON
                    // Add it to the viewer
                    viewer.dataSources.add(myDataSource);
                    // Remember the data source by ID so we can delete later
                    loadedGeometries[geometryID] = myDataSource;
                }, 'json');
                // SUCCESS! THIS PART WORKS!!
            } else {
                // unchecked, unload it from the map
                viewer.dataSources.remove(loadedGeometries[geometryID], true);
                delete loadedGeometries[geometryID];
                // FAILURE: OBJECT STILL ON THE MAP?!
            }
        });

几何图形按我的预期加载并显示,但当我取消选中该框时,数据仍保留在地图上。我不清楚 dataSource 上的 remove 函数是否在做我期望的事情。这是从显示中删除 DataSource 的正确方法吗?

这里的根本问题是 Cesium.GeoJsonDataSource.load 返回的是承诺,而不是真正的数据源。这意味着您正在尝试 .remove 数据源列表中的承诺,但这是行不通的。有趣的是,将承诺添加到数据源列表 确实 起作用,它只是被异步添加。无论如何试试这个:

Cesium.GeoJsonDataSource.load(data['points'], {
    markerSize: 24,
    markerColor: Cesium.Color.RED,
    markerSymbol: 't'
}).then(function(myDataSource) {
    // Add it to the viewer
    viewer.dataSources.add(myDataSource);
    // Remember the data source by ID so we can delete later
    loadedGeometries[geometryID] = myDataSource;
});

我要发表的另一条评论是,请查看 dataSource.show 标志。如果您认为用户会关闭并重新打开源,您可能不想从头开始卸载和重新加载它。您可以在它关闭时将 show 设置为 false,它会更快地恢复。它当然会继续消耗内存,但这没什么大不了的,除非它是 0.5 GB 或更多的数据。当显示为假时,它不会不必要地对 CPU 或 GPU 征税。