如何通过selectedEntity选中Cesium实体?代码执行未选中问题求助
Cesium实体选中问题解决办法
你当前代码的核心问题是:把DataSource数据源对象直接赋值给了viewer.selectedEntity,但这个属性要求传入的是单个Entity实体对象,而非整个数据源,所以选中状态不生效。
解决方案
根据需求选择以下两种方式:
1. 选中数据源下的所有实体
使用viewer.selectedEntities(复数形式)接收数据源的实体集合:
btn.onclick = function() { // 推荐用公开API遍历数据源,避免访问私有属性 viewer.dataSources.forEach(function(dataSource) { if (dataSource.name === btns_class[j].value) { // 选中当前数据源下的所有实体 viewer.selectedEntities = dataSource.entities.values; viewer.zoomTo(dataSource); } }); }
2. 选中数据源下的单个实体
从数据源的entities.values中取出具体的实体对象赋值给viewer.selectedEntity:
btn.onclick = function() { viewer.dataSources.forEach(function(dataSource) { if (dataSource.name === btns_class[j].value) { var entities = dataSource.entities.values; if (entities.length > 0) { // 选中第一个实体,可根据需求修改索引 viewer.selectedEntity = entities[0]; } viewer.zoomTo(dataSource); } }); }
额外提示
不要直接访问viewer.dataSources._dataSources这类下划线开头的私有属性,Cesium的私有属性可能会在版本更新中变更,使用viewer.dataSources.forEach()这种公开API更稳定。
内容的提问来源于stack exchange,提问作者Konsul
相关产品推荐
相关产品推荐

