Cesium 绘制点、线、面和测距
本文基于ES6,采用React+Cesium的Webgis前端开发框架,目前threejs和cesium的结合正在研究中。此段代码采用原生javascript,可能过程中用到了es6的扁平化语法,如()=>{},list.map方法。
废话不多说了,直接上代码。
import Cesium from 'cesium/Source/Cesium';
import monitor from '../style/images/monitor.jpeg'; const ECesium = {
version: '0.1',
description: '自定义cesium组件',
copyright: '2018-enbo'
}; ECesium.Tools = function (viewer, callback) {
this.viewer = viewer;
this.init();
}; ECesium.Tools.prototype.init = function (back) {
//初始化事件
const viewer = this.viewer;
const scene = viewer.scene;
this.drawingMode = null;
this.measureMode = null;
this.geodesic = new Cesium.EllipsoidGeodesic();
this.handler = new Cesium.ScreenSpaceEventHandler(scene.canvas); this.dataSource = new Cesium.CustomDataSource('test1');
viewer.dataSources.add(this.dataSource);
console.log(viewer.dataSources.indexOf(this.dataSource));
}; ECesium.Tools.prototype.draw = function (type) {
if (!this.viewer) return console.error('this.viewer 未定义');
this.deactivate();
this.drawingMode = type;
switch (type) {
case this.DRAW_TYPE.Point:
this.DrawPoint();
break;
case this.DRAW_TYPE.PolyLine:
case this.DRAW_TYPE.Polygon:
this.DrawGraphics();
break;
default:
break;
}
}; ECesium.Tools.prototype.DrawPoint = function (callback) {
const viewer = this.viewer;
const this_ = this;
this.drawingMode = "point";
this.handler.setInputAction(function (evt) {
const ray = viewer.camera.getPickRay(evt.position);
const mapPosition = this_.getMapPoint(ray);
if (!mapPosition) return;
this_.dataSource.entities.add({
id: '云台' + Math.random(),
name: '林火监测点',
position: Cesium.Cartesian3.fromDegrees(mapPosition.x, mapPosition.y, mapPosition.z),
point: new Cesium.PointGraphics({
color: Cesium.Color.SKYBLUE,
pixelSize: 10,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
}),
description: `<img style="height: 200px;" src=${monitor}>`
});
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}; ECesium.Tools.prototype.DrawGraphics = function (callback) {
const viewer = this.viewer;
const this_ = this;
let activeShapePoints = [];
let activeShape, floatingPoint;
this.handler.setInputAction(function (event) {
if (!Cesium.Entity.supportsPolylinesOnTerrain(viewer.scene)) {
return console.log('This browser does not support polylines on terrain.');
}
const ray = viewer.camera.getPickRay(event.position);
const earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
if (Cesium.defined(earthPosition)) {
if (activeShapePoints.length === 0) {
floatingPoint = this_.createPoint(earthPosition);
activeShapePoints.push(earthPosition);
const dynamicPositions = new Cesium.CallbackProperty(function () {
return activeShapePoints;
}, false);
activeShape = this_.drawShape(dynamicPositions);
} activeShapePoints.push(earthPosition);
this_.createPoint(earthPosition);
} }, Cesium.ScreenSpaceEventType.LEFT_CLICK); this.handler.setInputAction(function (event) {
if (Cesium.defined(floatingPoint)) {
const ray = viewer.camera.getPickRay(event.endPosition);
const newPosition = viewer.scene.globe.pick(ray, viewer.scene);
if (Cesium.defined(newPosition)) {
floatingPoint.position.setValue(newPosition);
activeShapePoints.pop();
activeShapePoints.push(newPosition);
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE); this.handler.setInputAction(function () {
terminateShape();
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK); function terminateShape() {
activeShapePoints.pop();
this_.drawShape(activeShapePoints);
this.dataSource.entities.remove(floatingPoint);
this.dataSource.entities.remove(activeShape);
floatingPoint = undefined;
activeShape = undefined;
activeShapePoints = [];
}
}; ECesium.Tools.prototype.getMapPoint = function (ray) {
const viewer = this.viewer;
const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
if (!cartesian) {
return null;
} const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
const lng = Cesium.Math.toDegrees(cartographic.longitude);//经度值
const lat = Cesium.Math.toDegrees(cartographic.latitude);//纬度值
//cartographic.height的值为地形高度。
return {x: lng, y: lat, z: cartographic.height};
}; ECesium.Tools.prototype.createPoint = function (worldPosition) {
return this.dataSource.entities.add({
position: worldPosition,
point: {
color: Cesium.Color.WHITE,
pixelSize: 5,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
}
});
}; ECesium.Tools.prototype.drawShape = function (positionData) {
switch (this.drawingMode) {
case this.DRAW_TYPE.PolyLine:
return this.dataSource.entities.add({
polyline: {
positions: positionData,
clampToGround: true,
width: 3
}
});
case this.DRAW_TYPE.Polygon:
return this.dataSource.entities.add({
polygon: {
hierarchy: positionData,
material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
}
});
default:
return;
}
}; ECesium.Tools.prototype.measure = function (type) {
this.deactivate();
this.measureMode = type;
this.DrawMeasureGraphics();
}; ECesium.Tools.prototype.DrawMeasureGraphics = function () {
const viewer = this.viewer;
const this_ = this;
let activeShapePoints = [];
let activeShape, floatingPoint;
let measureDistance = 0, floatDistance = 0;
this.handler.setInputAction(function (event) {
if (!Cesium.Entity.supportsPolylinesOnTerrain(viewer.scene)) {
return console.log('This browser does not support polylines on terrain.');
}
const ray = viewer.camera.getPickRay(event.position);
const earthPosition = viewer.scene.globe.pick(ray, viewer.scene);
if (Cesium.defined(earthPosition)) {
if (activeShapePoints.length === 0) {
floatingPoint = this_.createMeasurePoint(earthPosition);
if (this_.measureMode === this_.MEASURE_TYPE.MEASURE_DISTANCE) {
floatingPoint.label = {
text: new Cesium.CallbackProperty(function (time) {
let distance = floatDistance = this_.getLatestLength(activeShapePoints);
return ((distance + measureDistance) / 1000).toFixed(2) + ' km';
}, false),
showBackground: true,
backgroundColor: new Cesium.Color(0, 0, 0, 0.5),
backgroundPadding: new Cesium.Cartesian2(7, 5),
font: '16px sans-serif',
}; this_.createLabel(earthPosition, '起点')
}
activeShapePoints.push(earthPosition);
const dynamicPositions = new Cesium.CallbackProperty(function () {
return activeShapePoints;
}, false);
activeShape = this_.drawMeasureShape(dynamicPositions);
} if (activeShapePoints.length > 1 && this_.measureMode === this_.MEASURE_TYPE.MEASURE_DISTANCE) {
measureDistance += floatDistance;
this_.createLabel(earthPosition, (measureDistance / 1000).toFixed(2) + ' km');
} activeShapePoints.push(earthPosition);
this_.createMeasurePoint(earthPosition);
} }, Cesium.ScreenSpaceEventType.LEFT_CLICK); this.handler.setInputAction(function (event) {
if (Cesium.defined(floatingPoint)) {
const ray = viewer.camera.getPickRay(event.endPosition);
const newPosition = viewer.scene.globe.pick(ray, viewer.scene);
if (Cesium.defined(newPosition)) {
floatingPoint.position.setValue(newPosition);
activeShapePoints.pop();
activeShapePoints.push(newPosition);
}
}
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE); this.handler.setInputAction(function () {
terminateShape();
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK); function terminateShape() {
activeShapePoints.pop();
this_.drawMeasureShape(activeShapePoints);
this_.dataSource.entities.remove(floatingPoint);
this_.dataSource.entities.remove(activeShape);
floatingPoint = undefined;
activeShape = undefined;
activeShapePoints = [];
measureDistance = 0;
}
}; ECesium.Tools.prototype.drawMeasureShape = function (positionData, callback) {
console.log("draw shape");
switch (this.measureMode) {
case this.MEASURE_TYPE.MEASURE_DISTANCE:
return this.dataSource.entities.add({
polyline: {
positions: positionData,
clampToGround: true,
width: 3
}
});
case this.MEASURE_TYPE.MEASURE_AREA:
return this.dataSource.entities.add({
polygon: {
hierarchy: positionData,
material: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE.withAlpha(0.7))
}
});
default:
return;
}
}; ECesium.Tools.prototype.getLatestLength = function (activeShapePoints) {
const length = activeShapePoints.length;
const endPoint = activeShapePoints[length - 1];
const startPoint = activeShapePoints[length - 2];
const startCartographic = Cesium.Cartographic.fromCartesian(startPoint);
const endCartographic = Cesium.Cartographic.fromCartesian(endPoint);
this.geodesic.setEndPoints(startCartographic, endCartographic);
return Math.round(this.geodesic.surfaceDistance);
}; ECesium.Tools.prototype.createMeasurePoint = function (worldPosition, callback) {
return this.dataSource.entities.add({
position: worldPosition,
point: {
color: Cesium.Color.WHITE,
pixelSize: 8,
outlineColor: Cesium.Color.RED,
outlineWidth: 3,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
scaleByDistance: new Cesium.NearFarScalar(0, 0, 1, 1)
}
});
}; ECesium.Tools.prototype.createLabel = function (worldPosition, text) {
return this.dataSource.entities.add({
position: worldPosition,
label: {
text: text,
showBackground: true,
backgroundColor: new Cesium.Color(1, 1, 1, 0.7),
backgroundPadding: new Cesium.Cartesian2(7, 5),
font: '16px sans-serif',
fillColor: Cesium.Color.BLACK,
outlineColor: Cesium.Color.BLACK,
pixelOffset: new Cesium.Cartesian2(-15, -15)
}
});
}; ECesium.Tools.prototype.deactivate = function () {
if (this.handler) {
this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
} this.drawingMode = null;
}; ECesium.Tools.prototype.DRAW_TYPE = {
Point: 'Point',
PolyLine: 'PolyLine',
Polygon: 'Polygon'
}; ECesium.Tools.prototype.MEASURE_TYPE = {
MEASURE_DISTANCE: 'MeasureTerrainDistance',
MEASURE_AREA: 'MeasureTerrainArea'
};
export default ECesium;
使用时直接实例化ECesium
this.tool = new ECesium.Tools(this.viewer);
绘制图形
this.tool.draw('Point/PolyLine/Polygon');
测距
this.tool.measure(MeasureTerrainDistance);
Tips*面积测量没有添加计算方法,后期会加上。
Cesium 绘制点、线、面和测距的更多相关文章
- 【带着canvas去流浪(5)】绘制K线图
		
目录 一. 任务说明 二. 重点提示 三. 示例代码 示例代码托管在:http://www.github.com/dashnowords/blogs 博客园地址:<大史住在大前端>原创博文 ...
 - CAD交互绘制样条线(网页版)
		
在CAD设计时,需要绘制样条线,用户可以设置样条线线重及颜色等属性. 主要用到函数说明: _DMxDrawX::SendStringToExecuteFun 把命令当着函数执行,可以传参数.详细说明如 ...
 - CAD交互绘制样条线(com接口)
		
在CAD设计时,需要绘制样条线,用户可以设置样条线线重及颜色等属性. 主要用到函数说明: _DMxDrawX::SendStringToExecuteFun 把命令当着函数执行,可以传参数.详细说明如 ...
 - CAD参数绘制样条线(com接口)
		
在CAD设计时,需要绘制样条线,用户可以设置样条线线重及颜色等属性. 主要用到函数说明: _DMxDrawX::PathLineTo 把路径下一个点移到指定位置.详细说明如下: 参数 说明 DOUBL ...
 - CAD参数绘制样条线(网页版)
		
在CAD设计时,需要绘制样条线,用户可以设置样条线线重及颜色等属性. 主要用到函数说明: _DMxDrawX::PathLineTo 把路径下一个点移到指定位置.详细说明如下: 参数 说明 DOUBL ...
 - CAD动态绘制样条线(网页版)
		
在CAD设计时,需要绘制样条线,用户可以设置样条线线重及颜色等属性. 主要用到函数说明: _DMxDrawX::SendStringToExecuteFun 把命令当着函数执行,可以传参数.详细说明如 ...
 - 带着canvas去流浪系列之五 绘制K线图
		
[摘要] 用canvas原生API实现百度Echarts 示例代码托管在:http://www.github.com/dashnowords/blogs 一. 任务说明 使用原生canvasAPI绘制 ...
 - 用Python爬取股票数据,绘制K线和均线并用机器学习预测股价(来自我出的书)
		
最近我出了一本书,<基于股票大数据分析的Python入门实战 视频教学版>,京东链接:https://item.jd.com/69241653952.html,在其中用股票范例讲述Pyth ...
 - 使用Python的pandas模块、mplfinance模块、matplotlib模块绘制K线图
		
目录 pandas模块.mplfinance模块和matplotlib模块介绍 pandas模块 mplfinance模块和matplotlib模块 安装mplfinance模块.pandas模块和m ...
 - mapboxgl绘制3D线
		
最近遇到个需求,使用mapboxgl绘制行政区划图层,要求把行政区划拔高做出立体效果,以便突出显示. 拿到这个需求后,感觉很简单呀,只需要用fill-extrusion方式绘制就可以啦,实现出来是这个 ...
 
随机推荐
- 微软XAML Studio - WPF, Sliverlight, Xamarin, UWP等技术开发者的福音
			
目录 编辑器功能 数据源功能 调试数据绑定 伟大的开始 我们来一起实践吧 最近又在继续倒腾WPF的项目,继续使用Caliburn.Micro和Xceed来堆代码.每次调试xaml上的binding,都 ...
 - [asp.net core 源码分析] 01 - Session
			
1.Session文档介绍 毋庸置疑学习.Net core最好的方法之一就是学习微软.Net core的官方文档:https://docs.microsoft.com/zh-cn/aspnet/cor ...
 - Mybatis-Plus入门示例
			
1.内容: Mybatis-Plus只是在Mybatis的基础上,实现了功能增强,让开发更加简洁高效. Mybatis-Plus并没有修改Mybatis的任何特性. 2.入门示例: 2.1 需求:使用 ...
 - 关于页面传参,decodeURI和decodeURIComponent
			
之前写过一个关于页面传参的,但是是前端相对于自己的页面做的跳转,也就是页面1,跳转到页面2,里面带的参数.这里可以参考我上一篇文章,包括里面参数中如果有数组和json格式的情况.但是需要注意的是,我前 ...
 - 前端笔记之HTML
			
前端三层:内容层(结构层)HTML.样式层(表现层)CSS.行为层JavaScript 层 语言 含义 结构层 HTML 由 HTML 或 XHTML之类的标记语言负责创建.标签,也就是那些出现在尖括 ...
 - ArcGIS API for JavaScript 入门教程[6] 再讲数据——Map类之可操作图层
			
[回顾]上篇交代了Map是各种图层(不管是实际上的图层还是由图层构成的对象)的容器,是数据的容器,并不作显示(由视图类绘制).并重点讲解了由图层构成的复杂图层——高程属性ground和底图属性base ...
 - SuperMap iObject入门开发系列之六管线区域查询
			
本文是一位好友“托马斯”授权给我来发表的,介绍都是他的研究成果,在此,非常感谢. 管线区域查询功能针对单一管线图层进行区域多边形框选查询,然后将查询结果输出为列表,并添加定位和闪烁功能,效果如下图所示 ...
 - MySQL读取Binlog日志常见的3种错误
			
1. mysqlbinlog: [ERROR] unknown variable 'default-character-set=utf8mb4' 当我们在my.cnf中添加default-charac ...
 - SQL Server统计信息偏差影响表联结方式案例浅析
			
我们知道数据库中的统计信息的准确性是非常重要的.它会影响执行计划.一直想写一篇关于统计信息影响执行计划的相关博客,但是都卡在如何构造一个合适的例子上,所以一直拖着没有写.巧合,最近在生产环境中遇到 ...
 - Linux   初始环境配置 以及避坑  (详细)
			
没事儿喜欢自己装个虚拟机捣鼓捣鼓,经过几次装一些Linux 经验, 有时候 电脑了 .想重新系统了,又要重新去配置环境, 有时候又要去查很多很多命令 . 记录分享下Linux 下配置开发环境以及桌面 ...