Cesium快速入门到精通系列教程四:加载渲染GEOJSON数据
在 Cesium 1.93 中加载和渲染 GeoJSON 数据主要通过 GeoJsonDataSource 实现
一、基础加载方法
1. 直接加载本地/远程文件
const viewer = new Cesium.Viewer("cesiumContainer", {geocoder: false, //设置搜索框可见homeButton: false, // 返回初始位置键是否可见sceneModePicker: false, // 查看器选择模式选择键是否可见baseLayerPicker: false, // 图层选择键是否可见navigationHelpButton: false, // 是否显示帮助按钮animation: false, // 是否显示播放控制按钮timeline: false, // 是否显示时间轴fullscreenButton: false, // 是否显示全屏按钮});viewer.dataSources.add(Cesium.GeoJsonDataSource.load('https://geo.datav.aliyun.com/areas_v3/bound/100000.json', {stroke: Cesium.Color.HOTPINK,fill: Cesium.Color.BLUE,strokeWidth: 3,markerSymbol: '?'}));// https://geo.datav.aliyun.com/areas_v3/bound/100000.json也可以改成本地数据
或者使用以下方式
const viewer = new Cesium.Viewer("cesiumContainer", {geocoder: false, //设置搜索框可见homeButton: false, // 返回初始位置键是否可见sceneModePicker: false, // 查看器选择模式选择键是否可见baseLayerPicker: false, // 图层选择键是否可见navigationHelpButton: false, // 是否显示帮助按钮animation: false, // 是否显示播放控制按钮timeline: false, // 是否显示时间轴fullscreenButton: false, // 是否显示全屏按钮});Cesium.GeoJsonDataSource.load('https://geo.datav.aliyun.com/areas_v3/bound/100000.json', {stroke: Cesium.Color.HOTPINK,fill: Cesium.Color.PINK,strokeWidth: 3,markerSymbol: '?'}).then(dataSource => {viewer.dataSources.add(dataSource);});
二、样式自定义
1. 全局样式配置
加载时通过 options 参数设置默认样式:
viewer.dataSources.add(Cesium.GeoJsonDataSource.load('data/roads.geojson', {stroke: Cesium.Color.HOTPINK, // 轮廓颜色fill: Cesium.Color.PINK, // 填充颜色strokeWidth: 3 // 轮廓线宽})
);
三、性能优化(大规模数据)
当 GeoJSON 包含数万+面片时,建议使用 Primitive
替代 Entity
:
const features = geojsonData.features;
const instances = [];for (const feature of features) {const geometry = new Cesium.PolygonGeometry({polygonHierarchy: Cesium.PolygonHierarchy.fromDegreesArray(feature.geometry.coordinates[0])});instances.push(new Cesium.GeometryInstance({ geometry }));
}const primitive = new Cesium.Primitive({geometryInstances,appearance: new Cesium.EllipsoidSurfaceAppearance({material: Cesium.Material.fromType('Color', {uniforms: { color: new Cesium.Color(1.0, 0.0, 0.0, 0.8) }})})
});
viewer.scene.primitives.add(primitive);