cesium开发常用方法总结(拾取坐标,弹框信息跟随,地图视角切换,水面波浪效果,获取当前相机视角信息,绘制轨迹路线)

本文主要是介绍cesium开发常用方法总结(拾取坐标,弹框信息跟随,地图视角切换,水面波浪效果,获取当前相机视角信息,绘制轨迹路线),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

cesium 使用方法总结(持续更新)

cesiumNavigation使用(导航控件,比例尺等)
资源文件: 链接:https://pan.baidu.com/s/1jBDZdDTyaTU1LooO7LgJcA

提取码:uf37

全局:<script src="<%= BASE_URL %>CesiumNavigation/CesiumNavigation.umd.js"></script><link href="<%= BASE_URL %>CesiumNavigation/cesium-navigation.css" rel="stylesheet">
或者
npm install cesium-navigation-es6
import CesiumNavigation from 'cesium-navigation-es6'
 initCesiumNavigation(viewer: any) {const options: any = {}// 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.options.defaultResetView = new Cesium.Rectangle.fromDegrees(80, 22, 130, 50) // new Cesium.Rectangle.fromDegrees(113.8980, 22.4899, 113.9686, 22.5438)// 用于启用或禁用罗盘。true是启用罗盘,false是禁用罗盘。默认值为true。如果将选项设置为false,则罗盘将不会添加到地图中。options.enableCompass = true// 用于启用或禁用缩放控件。true是启用,false是禁用。默认值为true。如果将选项设置为false,则缩放控件将不会添加到地图中。options.enableZoomControls = true// 用于启用或禁用距离图例。true是启用,false是禁用。默认值为true。如果将选项设置为false,距离图例将不会添加到地图中。options.enableDistanceLegend = true// 用于启用或禁用指南针外环。true是启用,false是禁用。默认值为true。如果将选项设置为false,则该环将可见但无效。options.enableCompassOuterRing = trueCesiumNavigation(viewer, options)}
消除锯齿
// 消除锯齿removeJagged(viewer: any) {viewer.scene.postProcessStages.fxaa.enabled = falseviewer.scene.fxaa = falseconst supportsImageRenderingPixelated =viewer.cesiumWidget._supportsImageRenderingPixelatedif (supportsImageRenderingPixelated) {let vtxf_dpr = window.devicePixelRatiowhile (vtxf_dpr >= 2.0) {vtxf_dpr /= 2.0}viewer.resolutionScale = vtxf_dpr}}
坐标拾取,打印经纬度
eventMap(viewer) {var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)//拾取坐标handler.setInputAction((event) => {var earthPosition = viewer.camera.pickEllipsoid(event.position, viewer.scene.globe.ellipsoid);var cartographic = Cesium.Cartographic.fromCartesian(earthPosition, viewer.scene.globe.ellipsoid, new Cesium.Cartographic());var lat = Cesium.Math.toDegrees(cartographic.latitude);var lng = Cesium.Math.toDegrees(cartographic.longitude);var height = cartographic.height;console.log('经度'+lng+'纬度'+lat)}, Cesium.ScreenSpaceEventType.LEFT_CLICK);},
弹框标记跟随点击的位置

cesiumView:cesium的viewer对象
htmlOverlay:要操作的弹框对象(document.getElementbyId)
lng:经度值
lat:纬度值

htmlFixed(cesiumView, htmlOverlay, lng, lat) {const domHeight = htmlOverlay.offsetHeight; // DOM的高度const domWidth = htmlOverlay.offsetWidth; // DOM的宽度const heightOffset = 20; // Y轴偏移量const widthOffset = -9; // X轴偏移量const scratch = new Cesium.Cartesian2();cesiumView.scene.preRender.addEventListener(function() {var las = lat - 0.0009;let position = Cesium.Cartesian3.fromDegrees(lng, las, 2);let canvasPosition = cesiumView.scene.cartesianToCanvasCoordinates(position,scratch);if (Cesium.defined(canvasPosition)) {htmlOverlay.style.top = canvasPosition.y -domHeight -heightOffset + 'px';htmlOverlay.style.left = canvasPosition.x -domWidth / 2 -widthOffset + 'px';}});},
地球视角切换
mapFlyTo(viewer, lng, lat, height) {viewer.camera.flyTo({destination: new Cesium.Cartesian3.fromDegrees(lng, lat, height),duration: 3 //飞行时间})}
水面波浪效果
 // 湖面效果                     睡眠区域的坐标  cesium实例对象init_xianRiver(coordinates, viewer) {let coordinateArray = [];for (let index = 0; index < coordinates.length; index++) {for (let i = 0; i < coordinates[index].length; i++) {coordinateArray.push(coordinates[index][i][0]);coordinateArray.push(coordinates[index][i][1]);}}let outLinePositionArray = Cesium.Cartesian3.fromDegreesArray(coordinateArray);let riverPolygon = viewer.scene.primitives.add(new Cesium.Primitive({geometryInstances: new Cesium.GeometryInstance({geometry: new Cesium.PolygonGeometry({polygonHierarchy: new Cesium.PolygonHierarchy(outLinePositionArray),vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,height: 0,extrudedHeight: 0})}),appearance: new Cesium.EllipsoidSurfaceAppearance({aboveGround: true}),show: true}));
//增加水面效果riverPolygon.appearance.material = new Cesium.Material({fabric: {type: 'Water',uniforms: {normalMap: '../water.jpg',frequency: 1000.0,animationSpeed: 0.01,amplitude: 10.0}}});},
旋转平移缩放模型
//声明3Dtiles实例selFloorModel = new Cesium.Cesium3DTileset({url: floorInfo[7],maximumScreenSpaceError: 1,preferLeaves: true,});selFloorModel.readyPromise.then(() => {//创建xyz旋转矩阵var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(floorInfo[3]));var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(floorInfo[4]));var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(floorInfo[5]));//计算上述旋矩阵的结果var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);var rotationY = Cesium.Matrix4.fromRotationTranslation(my);var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);//平移 修改经纬度var position = Cesium.Cartesian3.fromDegrees(floorInfo[0],floorInfo[1],selFloorNum * 2.9);var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);//旋转、平移矩阵相乘Cesium.Matrix4.multiply(m, rotationX, m);Cesium.Matrix4.multiply(m, rotationY, m);Cesium.Matrix4.multiply(m, rotationZ, m);//缩放 修改缩放比例var pscale = Cesium.Matrix4.fromUniformScale(floorInfo[6]);Cesium.Matrix4.multiply(m, pscale, m);//赋值给tilesetselFloorModel._root.transform = m;//最后添加到实体中cesiumScene.primitives.add(selFloorModel);})
获取当前视角信息
getNowCamera: function () {//相机姿态var d = cesiumScene.camera;var heading = Cesium.Math.toDegrees(d.heading);var pitch = Cesium.Math.toDegrees(d.pitch);var roll = Cesium.Math.toDegrees(d.roll);let i = cesiumScene.camera.positionCartographic;let lat = Cesium.Math.toDegrees(i.latitude);let lng = Cesium.Math.toDegrees(i.longitude);return {heading: heading,pitch: pitch,roll: roll,centerx: lng,centery: lat,height: i.height,};},

绘制路线动态绘制,就是可以看到路线一点点画出

/******* * @function: function* @return {*}* @author: xk* @description: 绘制轨迹路线*/drawRoadLine(roadPosition) {let id = new Date().getTime();let arr = handlerRoadPath(roadPosition)// console.log(arr);let line = lineString(arr);/**计算规划的路径长度 */let roadLength = length(line, { units: 'meters' });/** 每秒100米的速度所需时间 */let time = Math.floor(roadLength / 100)if (time < 10) {time = "0" + time}let cartographicDegrees = handlerRoadPathTime(arr, time, 5 + 4)console.log(cartographicDegrees);let czml = [{id: "document",name: "CML Path" + id,version: "1.0",clock: {interval: `2012-08-04T10:00:00Z/2012-08-04T10:00:${time}Z`,currentTime: "2012-08-04T10:00:00Z",multiplier: 5,range: 'CLAMPED',},},{id: "path",name: "path wth GPS flight data" + id,availability: `2012-08-04T10:00:00Z/2012-08-04T10:00:${time}Z`,path: {material: {polylineOutline: {color: {rgba: [13, 188, 121, 255],},outlineColor: {rgba: [0, 255, 255, 255],},outlineWidth: 5,},},width: 10,leadTime: 0,resolution: 5,},billboard: {image: require('../../assets/images/billboardsImg/end.png'),eyeOffset: {cartesian: [0.0, 0.0, 0.0],},scale: 1.0},position: {epoch: "2012-08-04T10:00:00Z",cartographicDegrees: cartographicDegrees},},];if (window.removeEntities) {viewer.dataSources.remove(window.removeEntities, true)}window.removeEntities = Cesium.CzmlDataSource.load(czml);viewer.dataSources.add(Cesium.CzmlDataSource.load(czml)).then(function (ds) {window.removeEntities = ds;// 灵感记录// 如果要求不清除上一条路线,在czml加载完之后添加实体线 再清除czml});}

下面内容是为了方便作者本人日后开发copy使用,即项目初始化的一些操作封装

//
//Author: xingkang
//Date: 2022-11-14 14:25:53
//Description: 地图服务相关方法
//
/* eslint-disable */import Vue from 'vue'
import { lineString, length } from '@turf/turf'
import './skyBox/skyBoxGround'
import { handlerRoadPath, handlerRoadPathTime } from '../../utils/data-handler/dataChange.js';
/******* * @function: Class* @return {*}* @author: xk* @description: 初始化相关地图类*/
export class InitMap {constructor(container, camera, imageryProvider) {// /**轨迹坐标 */// this.track=null;this.container = container;this.camera = camera;this.imageryProvider = imageryProvider;// console.log(viewer);// this.mapEvent();}/******* * @function: function* @return {*}* @author: xk* @description: 初始化地图服务*/initMap() {const viewer = new Cesium.Viewer(this.container, {animation: false, //是否显示动画控件shouldAnimate: true,homeButton: false, //是否显示Home按钮fullscreenButton: false, //是否显示全屏按钮baseLayerPicker: false, //是否显示图层选择控件geocoder: false, //是否显示地名查找控件timeline: false, //是否显示时间线控件sceneModePicker: false, //是否显示投影方式控件navigationHelpButton: false, //是否显示帮助信息控件infoBox: false, //是否显示点击要素之后显示的信息requestRenderMode: false, //启用请求渲染模式scene3DOnly: true, //每个几何实例将只能以3D渲染以节省GPU内存sceneMode: 3, //初始场景模式 1 2.5D模式 2 2D循环模式 3 3D模式  selectionIndicator: false,// imageryProvider: this.imageryProvider,});viewer.scene.imageryLayers.removeAll(); //清除所有底图,此时地球是黑色viewer.scene.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({ //添加自己要的底图// url: `${Vue.prototype.$MapURL}/{z}/{x}/{y}.png`,// url: `${Vue.prototype.$MapURL}/binzhou-tiandimap/{z}/{x}/{y}.png`,url:  Cesium.buildModuleUrl("binzhou-tiandimap/{z}/{x}/{y}.png"),// url:  "assets/binzhou-tiandimap/{z}/{x}/{y}.png",// url: "http://106.15.228.37:8016/mapAndModel/map/{z}/{x}/{y}.png",maximumLevel: 18,rectangle: new Cesium.Rectangle( //当用的是自己裁剪的部分地图瓦片时,cesium报错确实瓦片的解决办法,坐标是裁剪的瓦片右上角左下角Cesium.Math.toRadians(118.085747845851),Cesium.Math.toRadians(38.279797333631315),Cesium.Math.toRadians(118.16425201890883),Cesium.Math.toRadians(38.31052094315904),)}))viewer.scene.globe.baseColor=Cesium.Color.BLACK; //场景基础颜色viewer.scene.moon.show = false; //月亮显示viewer.scene.sun.show = false; //太阳显示viewer.scene.skyAtmosphere.show=false; //大气viewer.scene.light = new Cesium.DirectionalLight({ //平行光direction: new Cesium.Cartesian3(0.354925, -0.890918, -0.283358)})viewer.scene.skyBox = new Cesium.GroundSkyBox({ //近地天空盒,这里用的封装插件,cesium自带的,近地会有倾斜,博客有详解自行翻sources: {positiveX: require('./skyBox/Right.jpg'),negativeX: require('./skyBox/Left.jpg'),positiveY: require('./skyBox/Front.jpg'),negativeY: require('./skyBox/Back.jpg'),positiveZ: require('./skyBox/Up.jpg'),negativeZ: require('./skyBox/Down.jpg')}})// 启用地形遮挡viewer.scene.globe.depthTestAgainstTerrain = true;viewer._cesiumWidget._creditContainer.style.display = 'none';// 是否支持图像渲染像素化处理if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {viewer.resolutionScale = window.devicePixelRatio;}//限制地图缩放级别// viewer.scene.screenSpaceCameraController.minimumZoomDistance = 10;// viewer.scene.screenSpaceCameraController.maximumZoomDistance = 10000;// 鼠标右键调整地图视角viewer.scene.screenSpaceCameraController.tiltEventTypes = [Cesium.CameraEventType.PINCH, Cesium.CameraEventType.RIGHT_DRAG];// 屏蔽Cesium的默认双击追踪选中entity行为viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);// 开启抗锯齿viewer.scene.postProcessStages.fxaa.enabled = true;return viewer;}/* 初始化相机视角 */setCameraView() {const { lng, lat, height, heading, pitch, roll } = this.camera;viewer.scene.camera.setView({destination: new Cesium.Cartesian3.fromDegrees(lng, lat, height),orientation: new Cesium.HeadingPitchRoll.fromDegrees(heading, pitch, roll)});}// 湖面效果async init_xianRiver(coordinates) {let coordinateArray = [];for (let index = 0; index < coordinates.length; index++) {for (let i = 0; i < coordinates[index].length; i++) {coordinateArray.push(coordinates[index][i][0]);coordinateArray.push(coordinates[index][i][1]);}}let outLinePositionArray = Cesium.Cartesian3.fromDegreesArray(coordinateArray);let riverPolygon = viewer.scene.primitives.add(new Cesium.Primitive({geometryInstances: new Cesium.GeometryInstance({geometry: new Cesium.PolygonGeometry({polygonHierarchy: new Cesium.PolygonHierarchy(outLinePositionArray),vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,height: 1,extrudedHeight: 0})}),appearance: new Cesium.EllipsoidSurfaceAppearance({aboveGround: true}),show: true}));riverPolygon.appearance.material = new Cesium.Material({fabric: {type: 'Water',uniforms: {baseWaterColor: Cesium.Color.fromCssColorString("#57aabc"),normalMap: require('./water.jpg'),frequency: 1000.0,animationSpeed: 0.01,amplitude: 10.0}}});}/******* * @function: function* @return {*}* @author: xk* @description: 获取当前窗口地图的视角信息*/getNowCamera() {//相机姿态const d = viewer.scene.camera;const heading = Cesium.Math.toDegrees(d.heading);const pitch = Cesium.Math.toDegrees(d.pitch);const roll = Cesium.Math.toDegrees(d.roll);const i = viewer.scene.camera.positionCartographic;const lat = Cesium.Math.toDegrees(i.latitude);const lng = Cesium.Math.toDegrees(i.longitude);return {heading: heading,pitch: pitch,roll: roll,centerx: lng,centery: lat,height: i.height};}/******* * @function: function* @return {*}customDataSource* @author: xk* @description: 添加广告牌和标签*/addBillOrLabel(imgUrl, position, cardId, type) {let a = viewer.entities.add({position: new Cesium.Cartesian3.fromDegrees(...position),cardId: cardId,type: type,billboard: {show: true,image: require("../../assets/images/billboardsImg/" + imgUrl),scale: 1.0,pixelOffset: new Cesium.Cartesian2(-86, -50),sizeInMeters: false,//控制以米为单位,缩放地图图片跟着缩放eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),horizontalOrigin: Cesium.HorizontalOrigin.LEFT,verticalOrigin: Cesium.VerticalOrigin.CENTER,distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000)}});return a}/*** @description: * @param {*} ent 实体* @param {*} options 可选 {duration: 3,	// 以秒为单位的飞行持续时间。maximumHeight: 2000,	// 飞行高峰时(切换视角时)的最大高度。offset : {heading : Cesium.Math.toRadians(0.0),	// 以弧度为单位的航向角。pitch : Cesium.Math.toRadians(-90),		// 以弧度为单位的俯仰角。range : 0								// 到中心的距离,以米为单位。}}* @return {*}*/flyToEntity(ent,options = {duration: 3, maximumHeight: 2000}){viewer.flyTo(ent,options);}/******* * @function: function* @return {*}* @author: xk* @description: 撒点方法*/addBillboard(billboards) {/**存放实例对象*/let billboardArr = []billboards.forEach((item, index) => {/**每个撒点的实例对象 */let billEntits = viewer.entities.add({// position: new Cesium.Cartesian3.fromDegrees(item.longitude,item.latitude, 5),position: new Cesium.Cartesian3.fromDegrees(...item.position, 5),dangerInfo: item.dangerInfo || '',cardId: item.id,type: item.type || '',name: item.name || '',sonType: item.equipmentType || item.alarmType || '',dataDetail: item.type=="油气浓度监测"?item:'',selfItem: item,billboard: {show: true,image: require(`../../assets/images/billboardsImg/${item.imgUrl}`),scale: 1.0,// rotation:Cesium.Math.toRadians(90),pixelOffset: new Cesium.Cartesian2(-32, -60),sizeInMeters: false,//控制以米为单位,缩放地图图片跟着缩放eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),horizontalOrigin: Cesium.HorizontalOrigin.LEFT,verticalOrigin: Cesium.VerticalOrigin.CENTER,distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000)},})billboardArr.push(billEntits)})viewer.zoomTo(billboardArr[0])return billboardArr;}/******* * @function: function* @return {*}* @author: xk* @description: 应急资源显示名称和数量*/addBillAndLabel(item) {let ent = viewer.entities.add({// position: new Cesium.Cartesian3.fromDegrees(118.12409366132542, 38.295807227591624, 5),position: new Cesium.Cartesian3.fromDegrees(...item.position, 5),// sonType: item.equipmentType || item.alarmType || '',billboard: {show: true,width: `${item.name}${item.number}(数量)`.length * 18,image: require("../../assets/images/infoBoxIcon/ssmalbox_blue.png"),scale: 1.0,// rotation:Cesium.Math.toRadians(90),pixelOffset: new Cesium.Cartesian2(-(`${item.name}${item.number}(数量)`.length * 18 / 2), -150),sizeInMeters: false,//控制以米为单位,缩放地图图片跟着缩放eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),horizontalOrigin: Cesium.HorizontalOrigin.LEFT,verticalOrigin: Cesium.VerticalOrigin.CENTER,distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000)},label: {show: true,text: `${item.name}${item.number} (数量)`,font: "16px Helvetica",fillColor: Cesium.Color.WHITE,// showBackground: true,// backgroundColor: Cesium.Color.BLACK.withAlpha(1),pixelOffset: new Cesium.Cartesian2(0, -152),distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000)}})return ent;}/******* * @function: function* @return {*}* @author: xk* @description:添加建筑标签 */addLabel() {viewer.entities.add({position: new Cesium.Cartesian3.fromDegrees(...position),type: 'building',label: {show: true,text: text,font: "14px Helvetica",fillColor: Cesium.Color.WHITE,showBackground: true,backgroundColor: Cesium.Color.BLACK}})}/******* * @function: function* @return {*}* @author: xk* @description: 展示应急路线*/addline(config) {const entities = []config.forEach(item => {let ent = viewer.entities.add({cardId: item.id,type: item.type,polyline: {positions: Cesium.Cartesian3.fromDegreesArrayHeights(item.positions),width: 20,material: new Cesium.PolylineArrowMaterialProperty(Cesium.Color.RED)}})entities.push(ent)})return entities;}/*******  118.12613093609299,38.29631968546674* @function: function* @return {*}nodelurl 模型地址* @author: xk* @description: 添加模型*/async addModel(modelInfo,viewer) {let { position, heading, modelUrl, pitch, roll, scale = 1.0 } = modelInfo;let area = new Cesium.Cartesian3.fromDegrees(...position);let hpr = new Cesium.HeadingPitchRoll(Cesium.Math.toRadians(heading), Cesium.Math.toRadians(pitch), Cesium.Math.toRadians(roll));let orientation = Cesium.Transforms.headingPitchRollToFixedFrame(area, hpr);let modelMatrix = orientationlet model = Cesium.Model.fromGltf({url:  modelUrl,// url: `${Vue.prototype.$ModelURL}${modelUrl}`,modelMatrix: modelMatrix,scale: scale});const modelObj = viewer.scene.primitives.add(model);return modelObj}/******* * @function: function* @return {*}* @author: xk* @description: 绘制轨迹路线*/drawRoadLine(roadPosition) {let id = new Date().getTime();let arr = handlerRoadPath(roadPosition)// console.log(arr);let line = lineString(arr);/**计算规划的路径长度 */let roadLength = length(line, { units: 'meters' });/** 每秒100米的速度所需时间 */let time = Math.floor(roadLength / 100)if (time < 10) {time = "0" + time}let cartographicDegrees = handlerRoadPathTime(arr, time, 5 + 4)// console.log(cartographicDegrees);let czml = [{id: "document",name: "CML Path" + id,version: "1.0",clock: {interval: `2012-08-04T10:00:00Z/2012-08-04T10:00:${time}Z`,currentTime: "2012-08-04T10:00:00Z",multiplier: 5,range: 'CLAMPED',},},{id: "path",name: "path wth GPS flight data" + id,availability: `2012-08-04T10:00:00Z/2012-08-04T10:00:${time}Z`,path: {material: {polylineOutline: {color: {rgba: [13, 188, 121, 255],},outlineColor: {rgba: [0, 255, 255, 255],},outlineWidth: 5,},},width: 10,leadTime: 0,resolution: 5,},billboard: {image: require('../../assets/images/billboardsImg/end.png'),eyeOffset: {cartesian: [0.0, 0.0, 0.0],},scale: 1.0},position: {epoch: "2012-08-04T10:00:00Z",cartographicDegrees: cartographicDegrees},},];if (window.removeEntities) {viewer.dataSources.remove(window.removeEntities, true)}window.removeEntities = Cesium.CzmlDataSource.load(czml);viewer.dataSources.add(Cesium.CzmlDataSource.load(czml)).then((ds)=> {window.removeEntities = ds;this.setCameraView()// viewer.trackedEntity = ds.entities.getById("path");// 获取当前地图瓦片级别// setTimeout(() => {//   console.log(time);//   viewer.camera.zoomOut(1000);// }, 3000);// 灵感记录// 如果要求不清除上一条路线,在czml加载完之后添加实体线 再清除czml});}/******* * @function: function* @return {*}* @author: xk* @description: 周界线 */boundaryAround(positions) {let flog = true;let x = 1;let entities = []positions.forEach(item => {let ent = viewer.entities.add({type: item.type,cardId: item.id,corridor: {positions: new Cesium.Cartesian3.fromDegreesArray(item.positions),width: 7,height: 1,extrudedHeight: 20,material: Cesium.Color.RED.withAlpha(0.5)// new Cesium.ColorMaterialProperty(new Cesium.CallbackProperty(function () {//   if (flog) {//     x = x - 0.05;//     if (x <= 0) {//       flog = false;//     }//   } else {//     x = x + 0.05;//     if (x >= 1) {//       flog = true;//     }//   }//   return Cesium.Color.RED.withAlpha(x);// }, false))},});entities.push(ent)})return entities;}}

绘制渐变色线条

//typescript 自行修改为js
getColorRamp(elevationRamp:Array<number>, isVertical:boolean = true) {const ramp = document.createElement('canvas');ramp.width = isVertical ? 1 : 100;ramp.height = isVertical ? 100 : 1;const ctx = ramp.getContext('2d');const values = elevationRamp;if (ctx) {const grd = isVertical ? ctx.createLinearGradient(0, 0, 0, 100) : ctx.createLinearGradient(0, 0, 100, 0);grd.addColorStop(values[0], '#ffff00');grd.addColorStop(values[1], '#ff0000');grd.addColorStop(values[2], '#00FF7E');ctx.globalAlpha = 0.3;ctx.fillStyle = grd;if (isVertical)ctx.fillRect(0, 0, 1, 100);elsectx.fillRect(0, 0, 100, 1);return ramp;}}addline(lineInfo: LineInfo) {const { position, width, color } = lineInfo;let lineColor = Cesium.Color.WHITE;const entities = this.viewer.entities.add({polyline: {// fromDegrees返回给定的经度和纬度值数组(以度为单位),该数组由Cartesian3位置组成。// Cesium.Cartesian3.fromDegreesArray([经度1, 纬度1, 经度2, 纬度2,])// Cesium.Cartesian3.fromDegreesArrayHeights([经度1, 纬度1, 高度1, 经度2, 纬度2, 高度2])positions: new Cesium.Cartesian3.fromDegreesArray(position),// 宽度width: width,// 线的颜色material: new Cesium.ImageMaterialProperty({image: this.getColorRamp([0.1, 0.5, 1.0], false),repeat: new Cesium.Cartesian2(1.0, 1),transparent: false,}),// material: lineColor,// 线的顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。// zIndex: 10,// 显示在距相机的距离处的属性,多少区间内是可以显示的distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 5000),// 是否显示show: true}})return entities;}

在这里插入图片描述

这篇关于cesium开发常用方法总结(拾取坐标,弹框信息跟随,地图视角切换,水面波浪效果,获取当前相机视角信息,绘制轨迹路线)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/361412

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

JS常用组件收集

收集了一些平时遇到的前端比较优秀的组件,方便以后开发的时候查找!!! 函数工具: Lodash 页面固定: stickUp、jQuery.Pin 轮播: unslider、swiper 开关: switch 复选框: icheck 气泡: grumble 隐藏元素: Headroom

无人叉车3d激光slam多房间建图定位异常处理方案-墙体画线地图切分方案

墙体画线地图切分方案 针对问题:墙体两侧特征混淆误匹配,导致建图和定位偏差,表现为过门跳变、外月台走歪等 ·解决思路:预期的根治方案IGICP需要较长时间完成上线,先使用切分地图的工程化方案,即墙体两侧切分为不同地图,在某一侧只使用该侧地图进行定位 方案思路 切分原理:切分地图基于关键帧位置,而非点云。 理论基础:光照是直线的,一帧点云必定只能照射到墙的一侧,无法同时照到两侧实践考虑:关

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

常用的jdk下载地址

jdk下载地址 安装方式可以看之前的博客: mac安装jdk oracle 版本:https://www.oracle.com/java/technologies/downloads/ Eclipse Temurin版本:https://adoptium.net/zh-CN/temurin/releases/ 阿里版本: github:https://github.com/

30常用 Maven 命令

Maven 是一个强大的项目管理和构建工具,它广泛用于 Java 项目的依赖管理、构建流程和插件集成。Maven 的命令行工具提供了大量的命令来帮助开发人员管理项目的生命周期、依赖和插件。以下是 常用 Maven 命令的使用场景及其详细解释。 1. mvn clean 使用场景:清理项目的生成目录,通常用于删除项目中自动生成的文件(如 target/ 目录)。共性规律:清理操作

业务中14个需要进行A/B测试的时刻[信息图]

在本指南中,我们将全面了解有关 A/B测试 的所有内容。 我们将介绍不同类型的A/B测试,如何有效地规划和启动测试,如何评估测试是否成功,您应该关注哪些指标,多年来我们发现的常见错误等等。 什么是A/B测试? A/B测试(有时称为“分割测试”)是一种实验类型,其中您创建两种或多种内容变体——如登录页面、电子邮件或广告——并将它们显示给不同的受众群体,以查看哪一种效果最好。 本质上,A/B测

git使用的说明总结

Git使用说明 下载安装(下载地址) macOS: Git - Downloading macOS Windows: Git - Downloading Windows Linux/Unix: Git (git-scm.com) 创建新仓库 本地创建新仓库:创建新文件夹,进入文件夹目录,执行指令 git init ,用以创建新的git 克隆仓库 执行指令用以创建一个本地仓库的

防近视护眼台灯什么牌子好?五款防近视效果好的护眼台灯推荐

在家里,灯具是属于离不开的家具,每个大大小小的地方都需要的照亮,所以一盏好灯是必不可少的,每个发挥着作用。而护眼台灯就起了一个保护眼睛,预防近视的作用。可以保护我们在学习,阅读的时候提供一个合适的光线环境,保护我们的眼睛。防近视护眼台灯什么牌子好?那我们怎么选择一个优秀的护眼台灯也是很重要,才能起到最大的护眼效果。下面五款防近视效果好的护眼台灯推荐: 一:六个推荐防近视效果好的护眼台灯的