概要
如题,cesium加载wkt格式的数据,wkt是Well Known Text 的缩写,是一种开放的国际标准,由OGC定义和维护,用于在计算机系统中交换空间地理数据,包含一些基本几何对象,点,线,面,多边形等等。
eg:“MULTIPOLYGON(((104.110525027242 30.5905346183995,104.110545942303 30.5905349932809,104.110546187199 30.5904777356401,104.110525027242 30.5905346183995)))”;
前面的POLYGON代表几何图形样式,后面的括号里的数据是图形对应的坐标。
wkt转GeoJSON
由于cesium不支持直接加载wkt格式的数据,但是我们可以利用wellknown.js库来将wkt格式的数据转换为geoJSON需要的几何坐标信息
// 安装
npm i wellknown
// 使用
import parse from 'wellknown';
// 传入wkt数据就可以得到geoJSON的几何数据了
const geometry = parse(wkt) // 就可以得到{type: 'MultiPolygon', coordinates: Array(1)}
由于接口一般返回的数据是wkt数据组成的数组,所以我们需要将数据处理为geoJSON的数据,然后让cesium加载
// 手动处理为GeoJSON
export const getGeoJSON = data => {
return {
type: 'FeatureCollection',
features: data.map(geometry => ({
type: 'Feature',
geometry: parse(geometry),
})),
};
};
cesium加载
cesium加载geoJSON需要利用dataSource加载
dataSource加载是异步的,加载完再把数据添加到视图中 viewer.dataSources.add();
// 加载GeoJSON数据
loadGeoJSON(geojson) {
const dataSource = new Cesium.GeoJsonDataSource();
dataSource
.load(geojson, {
clampToGround: true, // 贴地
})
.then(data => {
viewer.dataSources.add(data);
let entities = data.entities.values;
viewer.flyTo(data, {
offset: new Cesium.HeadingPitchRange(0, -45, 5000),
});
});
},
这样就加载完成了,只不过是二维的,没有立体效果
设置加载三维实体entities
需要拿到datasource的实体的值, data.entities.values拿到实体的数据,是一个数组
然后循环遍历给每一个实体设置材料属性信息。
let entities = data.entities.values;
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
entity.polygon.material = Cesium.Color.fromAlpha(Cesium.Color.GOLD, 0.8); //设置填充颜色
entity.polygon.outlineWidth = 4;
entity.polygon.outlineColor = Cesium.Color.GOLD; // 边框颜色'
entity.polygon.extrudedHeight = 10; //拉伸高度 米
entity.polygon.extrudedHeightReference = Cesium.HeightReference.RELATIVE_TO_GROUND; // 设置拉伸参照位置为地表
}
效果:
全部代码
loadGeoJSON(geojson) {
const viewer = window.viewer;
viewer.entities.removeAll(); // 移除点选地块的拉伸实体
if (viewer.dataSources) {
viewer.dataSources.removeAll();
}
const dataSource = new Cesium.GeoJsonDataSource();
dataSource
.load(geojson, {
clampToGround: true,
})
.then(data => {
viewer.dataSources.add(data);
let entities = data.entities.values;
for (let i = 0; i < entities.length; i++) {
let entity = entities[i];
entity.polygon.material = Cesium.Color.fromAlpha(Cesium.Color.GOLD, 0.8); //设置填充颜色
entity.polygon.outlineWidth = 4;
entity.polygon.outlineColor = Cesium.Color.GOLD; // 边框颜色'
entity.polygon.extrudedHeight = 10; //拉伸高度 米
entity.polygon.extrudedHeightReference = Cesium.HeightReference.RELATIVE_TO_GROUND; // 拉伸参照位置
}
viewer.flyTo(data, {
offset: new Cesium.HeadingPitchRange(0, -45, 5000),
});
});
},
};
有什么问题欢迎留言,一起探讨。