最近在学习cesium和react,将学习过程记录在此,供大家参考,可能有些写法不太标准或有错,还望指正。
(1)安装,环境部署
在react中使用cesium,先下载cesium;
npm install cesium
然后更改webpack.config.js的部分内容,参考1,参考2
(2)初始化地图
使用react函数式组件编写,需要使用useEffect,在界面初始化挂载的时候调用实现viewer的建立,并使用useRef以及.current保存下viewer,从而在useEffect外引用viewer。
import React,{useEffect,useRef} from 'react'
import * as Cesium from 'cesium'
export default function CesiumMap(){
var viewerRef = useRef(null)
useEffect(() => {
viewerRef.current = new Cesium.Viewer('cesiumContainer',{
terrain: Cesium.Terrain.fromWorldTerrain(),//地形
animation: false,
baseLayerPicker: true,
fullscreenButton: false,
vrButton: false,
geocoder: false,
homeButton: false,
infoBox: true,
sceneModePicker: false,
selectionIndicator: true,
timeline: false,
navigationHelpButton: false,
navigationInstructionsInitiallyVisible: false,
});
var viewer = viewerRef.current
viewer._cesiumWidget._creditContainer.style.display = "none";
viewer.scene.globe.enableLighting = true;// 开启全球光照
viewer.shadows = true
//初始位置
viewer.camera.setView({
destination:Cesium.Cartesian3.fromDegrees(113,23,1000), // 经纬度和高度
});
},[])
return(
<div id="cesiumContainer" style={{ width: '100%', height: '100%', position:'absolute', top:'0px',left:'0px'}} >
</div>
)
}
(3)加载数据
3DTiles(B3DM格式数据集)
viewer.scene.primitives.add(
new Cesium.Cesium3DTileset({
url: 'data/tiles/tileset.json',
})
);
WMS
var earthUrl = 'https://planetarymaps.usgs.gov/cgi-bin/mapserv?map=/maps/earth/earth_simp_cyl.map&service=WMS';
const earthLayer = new Cesium.ImageryLayer(
new Cesium.WebMapServiceImageryProvider({
url: earthUrl,
layers:'MODIS',
})
);
earthLayer.name = 'Earth'
viewer.imageryLayers.add(earthLayer);
GLB模型
//位置
const position = Cesium.Cartesian3.fromDegrees(
103,23,100
);
//camera姿态
const heading = Cesium.Math.toRadians(30);
const hpr = new Cesium.HeadingPitchRoll(heading, 0 ,0);
const orientation = Cesium.Transforms.headingPitchRollQuaternion(
position,hpr
);
const drone_entity = new Cesium.Entity({
id:'drone',
name: "无人机",
position: position,
orientation: orientation,
model: {
uri: "data/drone.glb",
scale:5,
// minimumPixelSize: 128,
// maximumScale: 200,
shadows:Cesium.ShadowMode.ENABLED
},
});
viewer.entities.add(drone_entity)
viewer.trackedEntity = drone_entity
Geojson
var dataSource = new Cesium.GeoJsonDataSource();
dataSource.name = 'layer'
viewer.dataSources.add(dataSource);
dataSource.load(
'data/area.json',{
fill:Cesium.Color(0,255,0),
}
).then(function(){
var entities = dataSource.entities.values;
for (var i = 0; i < entities.length; i++) {
var entity = entities[i];
//根据属性赋予不同颜色
var attributeValue = entity.properties.color._value;
if (attributeValue == 1) {
entity.polygon.material = Cesium.Color.GREEN;
} else{
entity.polygon.material = Cesium.Color.RED;
}
//厚度加0.1米,以避免被3dtiles遮挡
entity.polygon.extrudedHeight = entity.properties.z._value+0.1;
entity.polygon.outline = false;
entity.polygon.outlineColor = Cesium.Color(255,255,255);
}
})
点云数据
待添加