使用cesium笔记
官方案例demo:
1.https://sandcastle.cesium.com/?src=Geometry%20Height%20Reference.html
2.https://sandcastle.cesium.com/index.html?src=Clamp%20to%20Terrain.html
3.http://cesium.xin/cesium/cn/Documentation1.62/
使用:
1.申请令牌 https://blog.csdn.net/ljy1998dsb/article/details/124055029
2.页面中引用js,引用令牌
案例:
初始化地图(控件显隐及加载航拍数据)
initMap() { Cesium.Ion.defaultAccessToken = "xxx"; this.viewer = new Cesium.Viewer('cesiumContainer',{ geocoder:false,//查询按键 //homeButton:false,//home重置 //sceneModePicker:false,//切换2D、3D baseLayerPicker:false,//切换底图模式 navigationHelpButton:false,// 帮助提示,如何操作数字地球 animation:false,// 动画小组件 timeline:false, fullscreenButton:false,// 全屏组件 sceneMode: 3, }); // 隐藏logo this.viewer._cesiumWidget._creditContainer.style.display = "none"; const terrainTileset = this.viewer.scene.primitives.add( new Cesium.Cesium3DTileset({ url: "http://ip:33114/3DData/JiaoZuo/terra_b3dms/tileset.json", maximumScreenSpaceError: 1, loadSiblings: true, // 如果为true则不会在已加载完概况房屋后,自动从中心开始超清化房屋 cullRequestsWhileMovingMultiplier: 10, // 值越小能够更快的剔除 // maximumMemoryUsage: 128, // 内存分配变小有利于倾斜摄影数据回收,提升性能体验 progressiveResolutionHeightFraction: 0.5, // 数值偏于0能够让初始加载变得模糊 dynamicScreenSpaceErrorDensity: 0.5, // 数值加大,能让周边加载变快 dynamicScreenSpaceErrorFactor: 1, // 不知道起了什么作用没,反正放着吧先 dynamicScreenSpaceError: true, // 根据测试,有了这个后,会在真正的全屏加载完之后才清晰化房屋 }) ); this.viewer.scene.globe.depthTestAgainstTerrain = true; this.viewer.camera.flyTo({ destination: new Cesium.Cartesian3.fromDegrees(113.3182509, 35.3256581, 1200) }) this.scene = this.viewer.scene; this.canvas = this.viewer.scene.canvas; }
请求接口,显示glb模型
addWaJi() { getExcavator().then((res) => { // console.log('挖机最新位置', res); if (res.status == 200 && res.data.data.length > 0) { res.data.data.forEach((item) => { var longitude = item.longitude; var latitude = item.latitude; var height = item.height; const position3 = new Cesium.Cartesian3.fromDegrees(longitude,latitude,0); var car = this.viewer.entities.add({ name: '挖机', position: position3, model: { uri: './wj-y.glb', minimumPixelSize: 50, maximumScale: 20000, //heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, // clampToGround: true RELATIVE_TO_GROUND CLAMP_TO_GROUND }, }); calculateHeading(car, longitude,latitude); // let pos = await getClampHeight(position2); // car.position = pos[0];//position2; car.label={ text: '挖机', color : Cesium.Color.BLUE, font:'normal 32px MicroSoft YaHei', showBackground : true, scale : 0.5, horizontalOrigin : Cesium.HorizontalOrigin.LEFT_CLICK, verticalOrigin : Cesium.VerticalOrigin.BOTTOM, disableDepthTestDistance : 100000.0 }; car.description = '<div style="height: 50px;">'+"123"+'</div>'; this.wajiList.push(car); //挖机贴地,接口返回的高度不适用 clamp3DTiles(car, longitude, latitude, this.wajiList, this.viewer); }); } }); },
//获取所有挖机最新位置 export const getExcavator = (processInstanceId) => { return request({ url: '/api/integrated-services-manager/device/excavatorList', method:'post', }) }
刷新接口,呈现小车在路上跑的动画(包含 贴地及方向计算)
mapDataone() { getDispatchPoints().then(async (res) => { if (res && res.data && res.data.data && res.data.data.bogies && res.data.data.bogies.length > 0) { if (this.carList.length == 0) { //将车辆添加到地图上 res.data.data.bogies.forEach((item) => { var entityObj = this.viewer.entities.add({ show: true, position: Cesium.Cartesian3.fromDegrees( item.longitude, item.latitude, 0 ), // 初始朝向 orientation: Cesium.Transforms.headingPitchRollQuaternion( Cesium.Cartesian3.fromDegrees(item.longitude, item.latitude, 0), new Cesium.HeadingPitchRoll( Cesium.Math.toRadians(item.heading ? (item.heading - 90) : -90), // 设置这个属性即可(顺时针旋转的角度值) Cesium.Math.toRadians(0), Cesium.Math.toRadians(0) ) ), }); // 卡车使用3d模型,挖掘机暂时使用图片 //1:挖机 2:矿卡 3:有人车 4:推土机 if (item.carType == 1) { entityObj.model = { uri: './wj-y.glb', // 加载模型 minimumPixelSize: 50 // 指定模型大小 } } else if(item.carType == 2){ entityObj.model = { uri: './kuangche-y.glb', // 加载模型 minimumPixelSize: 50 // 指定模型大小 } entityObj.model.lightColor = new Cesium.Cartesian3(15, 15, 15) entityObj.model.shadows = Cesium.ShadowMode.DISABLED } entityObj.info = item // 赋值相关属性 entityObj.preLng = item.longitude entityObj.preLat = item.latitude this.carList.push(entityObj) }); } else { //更新车辆位置 res.data.data.bogies.forEach((item) => { // console.log("车辆位置 "+item.deviceId,item.longitude,item.latitude); var entity = this.getEntity(item.deviceId); if (entity != null) { // 贴地,解决屏幕切换问题,一直停留在该页面时不触发,切屏出去后触发,页面切回来后先将最后点贴地处理 if (entity.preLng && entity.preLat) { clamp3DTiles(entity, entity.preLng, entity.preLat, this.carList, this.viewer) } entity.preLng = null entity.preLat = null console.log("车辆位置========== "+item.deviceId,item.longitude,item.latitude); var lnglat = [item.longitude, item.latitude] var height = 0 var cartesianPre = new Cesium.Cartesian3(entity.position._value.x, entity.position._value.y, entity.position._value.z) var cartographicPre = Cesium.Cartographic.fromCartesian(cartesianPre)//之前的位置 // 前后坐标相差不多,直接false var lngOld = Cesium.Math.toDegrees(cartographicPre.longitude); var latOld = Cesium.Math.toDegrees(cartographicPre.latitude); var differLon = lnglat[0] - lngOld; var differLat = lnglat[1] - latOld; if (Math.abs(differLon) < 1e-5 && Math.abs(differLat) < 1e-5) { // console.log('距离过小'); clamp3DTiles(entity, item.longitude, item.latitude, this.carList, this.viewer); // return false } else { // console.log(item.deviceId) entity.lngX = (differLon) / 5 entity.lngY = (differLat) / 5 // entity.isFnished = (entity.lngX > 0) ? 'true' : 'false' // 计算航向角 calculateHeading(entity, item.longitude, item.latitude) // console.log('。。。。。。。。。。。。。。。。。'); if (entity.setInterval) { clearInterval(entity.setInterval); // window.clearInterval(entity.setInterval) this.moveFlag = false; // console.log('clear timer'); entity.refreshIndex = 0;//刷新次数,总共五次 } entity.setInterval = setInterval(() => { entity.refreshIndex = entity.refreshIndex + 1; if (entity.refreshIndex > 5) { entity.refreshIndex = 0; if (entity.setInterval) { clearInterval(entity.setInterval); // window.clearInterval(entity.setInterval) // this.moveFlag = false; // console.log('clear timer'); } } this.moveFlag = true; if (this.moveFlag) { // console.log('move'); } else { // console.log('stop'); } // 长时间不推送时需进行判断是否达到最后推送位置 // var cartesian = new Cesium.Cartesian3(entity.position._value.x, entity.position._value.y, entity.position._value.z) // var cartographic = Cesium.Cartographic.fromCartesian(cartesian) var lng = lngOld + entity.lngX*entity.refreshIndex;//新位置 var lat = latOld + entity.lngY*entity.refreshIndex if (lng == item.longitude && lat == item.latitude) { // console.log('相等'); } else { // console.log('ding'+entity.lngX+' lngOld - lng = '+lngOld+'-'+lng); } // var alt = cartographic.height + entity.lngZ // 判断是否到达目标终点 // if ((lng < lnglat[0] && entity.isFnished === 'true') || (entity.isFnished === 'false' && lng > lnglat[0])) { if(lng != lnglat[0] && lat != lnglat[1]){ // if(entity.isFnished === 'false'){ // entity.position = Cesium.Cartesian3.fromDegrees(lng, lat, alt) // 实时贴地 clamp3DTiles(entity, lng, lat, this.carList, this.viewer) } else { if (entity.setInterval) { clearInterval(entity.setInterval); // window.clearInterval(entity.setInterval) this.moveFlag = false; // console.log('clear timer'); } entity.setInterval = null } }, 600); } } }); } } }); }
4秒刷新一次位置
this.times = setInterval(() => { this.mapDataone(); }, 4000);
叠加点线面(作业区、作业点、线路)
surfaceData() { surfaceDataApi().then(res => { // console.log('开采区', res); if (res.status == 200 && res.data.data.length > 0) { res.data.data.forEach((item) => { polygonRegn(item, this.viewer, this.polygonArr); }); } }); }, lineData() { lineDataApi().then(res => { // console.log('路线', res); if (res.status == 200 && res.data.data.length > 0) { res.data.data.forEach((data) => { console.log('路线1111', data); var positions = [] data.geometry.coordinates.forEach(item => { positions.push(Cesium.Cartesian3.fromDegrees(parseFloat(item[0]), parseFloat(item[1]), 0)); }) var entityPolyline = this.viewer.entities.add({ polyline: { positions: positions, width: 3, material: new Cesium.PolylineGlowMaterialProperty({ glowPower: .1, //一个数字属性,指定发光强度,占总线宽的百分比。 color: Cesium.Color.CYAN.withAlpha(.9) }), clampToGround: true }, show: true, }); const name = data.properties.名称; const code = data.properties.编号; const created = data.properties.创建时间; //const center = data.properties.中心点; entityPolyline.description = "<img width=\"50{ac3c4da2cd0600a7fb5dd7ece3d30a0eed29da11cf2830143610191d982c65a1}\" style=\"float:left; margin: 0 1em 1em 0;\" src=\"./point.png\"/>"+ "<p>道路名称:"+name+"</p>"+ "<ul style='list-style: none;'>"+ "<li>编号:"+code+"</li>"+ "<li>创建时间:"+created+"</li>"+ //"<li>中心点:"+center+"</li>"+ "</ul>"+ //"<p>Source:<a style=\"color: WHITE\" target=\"_blank\" href=\"http://en.wikipedia.org/wiki/Wyoming\">Wikpedia</a>"+ "</p>"; var entityLabel = this.viewer.entities.add({ position: Cesium.Cartesian3.fromDegrees(data.properties.中心点[0], data.properties.中心点[1]), label:{ text: name, color: Cesium.Color.fromCssColorString("#fff"), font: "normal 32px MicroSoft YaHei", showBackground: true, scale: 0.5, horizontalOrigin: Cesium.HorizontalOrigin.LEFT_CLICK, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, disableDepthTestDistance: 100000.0, distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000) }, show:true, }); // 异步要素贴地(等待倾斜摄影加载完毕) var startPosition = _.cloneDeep(entityLabel.position._value) this.viewer.scene.clampToHeightMostDetailed([entityLabel.position._value]).then(function (clampCartesians) { if (clampCartesians[0]) { var cartographic = Cesium.Cartographic.fromCartesian(clampCartesians[0]) // 结果对象中的值将以弧度表示。 var height = Number(cartographic.height) if (height < (-1500)) { entityLabel.position = startPosition } else { } } else { entityLabel.position = startPosition } }); this.polylineArr.push(entityPolyline); this.polylineArr.push(entityLabel); }); } }); }, pointData() { pointDataApi().then((res) => { // console.log('作业点', res); if (res.status == 200 && res.data.data.length > 0) { res.data.data.forEach((item) => { console.log('item', item); const name = item.properties.名称; const code = item.properties.编号; const created = item.properties.创建时间; var pointEntity = this.viewer.entities.add({ position: Cesium.Cartesian3.fromDegrees(parseFloat(item.geometry.coordinates[0]),parseFloat(item.geometry.coordinates[1]),parseFloat(item.geometry.coordinates[2])+2), billboard: { image: "./point.png", width: 60, height:60, }, label: { text: name, color: Cesium.Color.fromCssColorString("#fff"), font: "normal 32px MicroSoft YaHei", showBackground: true, scale: 0.5, horizontalOrigin: Cesium.HorizontalOrigin.LEFT_CLICK, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, disableDepthTestDistance: 100000.0, pixelOffset: new Cesium.Cartesian2(0, -70), distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000), show:false }, show:true, }); pointEntity.description = "<img width=\"50{ac3c4da2cd0600a7fb5dd7ece3d30a0eed29da11cf2830143610191d982c65a1}\" style=\"float:left; margin: 0 1em 1em 0;\" src=\"./point.png\"/>"+ "<p>作业点名称:"+name+"</p>"+ "<ul style='list-style: none;'>"+ "<li>编号:"+code+"</li>"+ "<li>创建时间:"+created+"</li>"+ "</ul>"+ //"<p>Source:<a style=\"color: WHITE\" target=\"_blank\" href=\"http://en.wikipedia.org/wiki/Wyoming\">Wikpedia</a>"+ "</p>"; const handler = new Cesium.ScreenSpaceEventHandler(this.canvas); handler.setInputAction((movement) => { let foundPosition = false; if (this.scene.mode !== Cesium.SceneMode.MORPHING) { const pickedObject = this.scene.pick(movement.endPosition); if ( this.scene.pickPositionSupported && Cesium.defined(pickedObject) && pickedObject.id === pointEntity ) { console.log('item', item); pointEntity.label.show = true; pointEntity.label.text = `名称: ${` ${name}`}\u00B0` + `\n编号: ${` ${code}`}\u00B0` + `\n创建时间: ${` ${created}`}m`; pointEntity.label.eyeOffset = new Cesium.Cartesian3( 0.0, 0.0, -cartographic.height * (this.scene.mode === Cesium.SceneMode.SCENE2D ? 1.5 : 1.0) ); foundPosition = true; } } if (!foundPosition) { pointEntity.label.show = false; } }, Cesium.ScreenSpaceEventType.MOUSE_MOVE); this.pointArr.push(pointEntity); }); } }); }, }