Cesium CustomDataSource 详解
在 Cesium 中,CustomDataSource 是一个强大的类,用于处理自定义的地理数据。它提供了一种方法,可以通过程序方式添加、管理和更新动态的地理实体,而无需依赖外部数据格式(如 GeoJSON 或 CZML)。
CustomDataSource 的作用
自定义数据管理:可以创建和管理自己的实体集合。
动态更新:能够动态地添加、移除和更新实体。
与场景交互:实体可以绑定到 Cesium 的场景中,与其他数据源和图层结合使用。
使用步骤
1. 创建 CustomDataSource
要使用 CustomDataSource,需要先实例化它:
const viewer = new Cesium.Viewer("cesiumContainer"); // 创建一个 CustomDataSource const customDataSource = new Cesium.CustomDataSource("myDataSource"); // 将数据源添加到 viewer viewer.dataSources.add(customDataSource);
"myDataSource" 是这个数据源的名称,可以用于管理和调试。
2. 添加实体到 CustomDataSource
可以使用 CustomDataSource.entities 添加或管理实体。
const entity = customDataSource.entities.add({ id: "uniqueId", // 可选,指定实体的唯一标识符 name: "Example Entity", position: Cesium.Cartesian3.fromDegrees(114.169, 22.319, 100), point: { pixelSize: 10, color: Cesium.Color.RED, }, label: { text: "Hello Cesium", font: "14pt sans-serif", fillColor: Cesium.Color.WHITE, }, }); // 如果需要,可以随时更新实体的属性 entity.position = Cesium.Cartesian3.fromDegrees(120.0, 30.0, 200); entity.point.pixelSize = 15;
3. 动态更新数据
CustomDataSource 非常适合动态场景,例如实时数据流的可视化。
添加实体:
customDataSource.entities.add({ position: Cesium.Cartesian3.fromDegrees(120.0, 40.0, 300), point: { pixelSize: 5, color: Cesium.Color.BLUE, }, });
移除实体:
customDataSource.entities.remove(entity); // 删除指定实体 customDataSource.entities.removeAll(); // 删除所有实体
查找实体:
const foundEntity = customDataSource.entities.getById("uniqueId"); if (foundEntity) { console.log("找到实体:", foundEntity.name); }
4. 监听实体变化
CustomDataSource 支持监听实体集合的变化,例如添加或移除实体时触发回调。
customDataSource.entities.collectionChanged.addEventListener((collection, added, removed, changed) => { console.log("添加的实体:", added); console.log("移除的实体:", removed); console.log("改变的实体:", changed); });
典型应用场景
实时监控:如飞机或卫星的实时轨迹。
用户交互:动态添加标记点或绘制区域。
数据可视化:处理非标准格式的数据,按需展示。
其他重要方法和属性
属性
name:数据源的名称。
entities:数据源中包含的实体集合。
isLoading:数据源是否正在加载数据。
clock:关联的时钟,用于控制时间相关的实体。
方法
load():加载数据,可以从外部数据源初始化实体。
update():用于手动更新数据源(通常不需要手动调用)。
destroy():销毁数据源,释放资源。
完整示例
下面是一个使用 CustomDataSource 创建多个动态实体的完整示例:
const viewer = new Cesium.Viewer("cesiumContainer"); // 创建自定义数据源 const customDataSource = new Cesium.CustomDataSource("dynamicData"); viewer.dataSources.add(customDataSource); // 动态添加实体 setInterval(() => { const lon = Math.random() * 360 - 180; const lat = Math.random() * 180 - 90; const height = Math.random() * 1000; customDataSource.entities.add({ position: Cesium.Cartesian3.fromDegrees(lon, lat, height), point: { pixelSize: 10, color: Cesium.Color.YELLOW, }, label: { text: `Lat: ${lat.toFixed(2)}, Lon: ${lon.toFixed(2)}`, font: "10pt sans-serif", fillColor: Cesium.Color.WHITE, }, }); }, 1000); // 删除所有实体按钮 const button = document.createElement("button"); button.textContent = "删除所有实体"; button.onclick = () => customDataSource.entities.removeAll(); document.body.appendChild(button);
总结
CustomDataSource 是 Cesium 中一个灵活且高效的工具,适合处理动态变化的数据。在开发中,你可以利用它实现实时数据可视化、用户交互等功能,并根据需求动态管理实体集合。