learning_cesium/在线编辑-path.html

541 lines
22 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<!-- Use correct character set. -->
<meta charset="utf-8" />
<!-- Tell IE to use the latest, best version. -->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- Make the application on mobile take up the full browser screen and disable user scaling. -->
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
/>
<title>Learning Cesium!</title>
<script src="./Build/Cesium/Cesium.js"></script>
<style>
@import url(./Build/Cesium/Widgets/widgets.css);
html,
body,
#app,
#cesiumContainer {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
.menu-container {
position: absolute;
top: 30px;
left: 100px;
z-index: 9999;
}
</style>
<!-- 引入样式 -->
<link rel="stylesheet" href="./js/elementui/index.css" />
<!-- import Vue before Element -->
<script src="./js/vue2710.js"></script>
<!-- import JavaScript -->
<script src="./js/elementui/index.js"></script>
</head>
<body>
<div id="app">
<div class="menu-container">
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<el-breadcrumb separator="/">
<el-breadcrumb-item>cesium</el-breadcrumb-item>
<el-breadcrumb-item>绘制功能</el-breadcrumb-item>
<el-breadcrumb-item>点、线、面</el-breadcrumb-item>
</el-breadcrumb>
</div>
</el-col>
</el-row>
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<cesiumComponent id="cesium" ref="refCesium" />
</div>
</el-col>
</el-row>
<el-row type="flex" :gutter="20">
<el-col :span="24">
<div class="grid-content bg-purple">
<el-button type="primary" @click="draw">绘制path</el-button>
<el-button type="primary" @click="clearDrawEntities"
>清空</el-button
>
</div>
</el-col>
</el-row>
</div>
<div
id="tooltip"
style="
position: absolute;
z-index: 999;
background: rgba(0, 0, 0, 0.3);
color: rgb(255, 255, 255);
font-size: 12px;
padding: 5px;
border-radius: 5px;
"
>
左键点击选点,右键也可取消
</div>
<div id="cesiumContainer"></div>
</div>
<script>
Cesium.Ion.defaultAccessToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ZjRjNTZkNC01NDYxLTRhMjQtOGEwZC1kZjA3YzQ5YTJlZDkiLCJpZCI6MjYwODQsInNjb3BlcyI6WyJhc3IiLCJnYyJdLCJpYXQiOjE1ODcxOTMwODN9.prGsSKyAW_9Ow5zHYPhbm3LsQL-ApQw5-5PNJkDaHi8";
new Vue({
el: "#app",
data() {
return {
polygonPointsEntities: [], // 区域的点位集合
polygonPointsEntitiesLine: [], // 连线的多点
polygonPointsEntitiesEntity: [], // 区域查询所画线实体
pointPositionList: [], // 画点的经纬度集合
editPoints: [], // 编辑时编辑点集合,删除点用
isAddStatus: false, // 是否是添加区域
isEditStatus: false, // 是否是编辑区域
isAddPoint: false, //是否新添加了点
spaceArea: "", // 区域范围坐标
polygonEntity: null, // 区域面实体
isSaved: false, // 保存状态
viewer: null, // 地图实例化
curBillboard: null, // 当前高亮的广告牌
entityMarkerList: [], // 地图上点的资源实体对象集合
companyPoint: [], // 企业上点数据
// 标注图层
// tdtImgAnnoLayerProvider:
// new Cesium.WebMapTileServiceImageryProvider({
// url: "http://t6.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=b6b320a7ccfabfdc30536330efc07f3e",
// layer: "tdtImgAnnoLayer",
// style: "default",
// format: "image/jpeg",
// tileMatrixSetID: "GoogleMapsCompatible",
// }),
_viewer: undefined,
tempEntities: [],
pathPoints: [],
testPoints: [
[113.093199, 23.085135, 200],
[113.39194, 23.478276, 200],
[114.078169, 23.330206, 200],
[114.141996, 22.994195, 200],
[113.699341, 22.817996, 200],
],
};
},
mounted() {
this.initMap(113.666612, 22.249119, 40000);
},
methods: {
// 初始化地图(根据当前企业所在位置初始化中心位置)
initMap(longitude, latitude, height) {
Cesium.Ion.defaultAccessToken =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNjJkN2ZjNC04OTYxLTQyZmItYmM5Mi0yOTgyMzQxMjEzZGQiLCJpZCI6MTg5NTIsInNjb3BlcyI6WyJhc2wiLCJhc3IiLCJhc3ciLCJnYyIsInByIl0sImlhdCI6MTU4OTYyODkwMn0.ibuCu13_8ksLkyimUHR4e1LrWRb-_sfZrPMhSWSzJBg";
let viewer = new Cesium.Viewer("cesiumContainer", {
baseLayerPicker: false,
geocoder: false, // 是否显示地名查找控件
homeButton: false,
sceneModePicker: false, // 是否显示投影方式控件
selectionIndicator: false,
baseLayerPicker: false, // 是否显示图层选择控件
navigationHelpButton: false, // 是否显示帮助信息控件
animation: false, // 是否显示动画控件
// creditContainer: "credit",
timeline: true, // 是否显示时间线控件
fullscreenButton: false,
vrButton: false,
infoBox: false, // 是否显示点击要素之后显示的信息
// requestRenderMode: true, // 启用请求渲染模式
scene3DOnly: true, // 每个几何实例将只能以3D渲染以节省GPU内存
sceneMode: 3, // 初始场景模式 1 2D模式 2 2D循环模式 3 3D模式 Cesium.SceneMode
// imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
// url: "http://t0.tianditu.gov.cn/img_w/wmts?tk=b6b320a7ccfabfdc30536330efc07f3e",
// layer: "img",
// style: "default",
// tileMatrixSetID: "w",
// format: "tiles",
// maximumLevel: 18,
// }),
});
this._viewer = viewer;
viewer.imageryLayers.removeAll();
viewer.imageryLayers.addImageryProvider(
new Cesium.ArcGisMapServerImageryProvider({
url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer",
// url: "https://map.geoq.cn/arcgis/rest/services/ChinaOnlineStreetGray/MapServer",
// url: "https://map.geoq.cn/arcgis/rest/services/ChinaOnlineCommunityENG/MapServer",
})
);
viewer._cesiumWidget._creditContainer.style.display = "none";
viewer.scene.globe.depthTestAgainstTerrain = true; // 图标被遮挡
viewer.scene.fxaa = false;
viewer.scene.globe.enableLighting = true;
// 设置后当相机高度达到设置的最大和最小高度时将不再放大和缩小
// viewer.scene.screenSpaceCameraController.minimumZoomDistance = 0; // 相机的高度的最小值
// viewer.scene.screenSpaceCameraController.maximumZoomDistance = 20000000; // 相机高度的最大值
// 天地图矢量标注图层
// this.tdtImgAnnoLayer = viewer.imageryLayers.addImageryProvider(
// this.tdtImgAnnoLayerProvider
// );
// viewer.imageryLayers.raiseToTop(this.tdtImgAnnoLayer);
// 定位到中心点
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
Number(longitude),
Number(latitude),
height
),
orientation: {
heading: Cesium.Math.toRadians(20.0),
pitch: Cesium.Math.toRadians(-35.0),
roll: 0.0,
},
});
// 关闭双击事件
viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
);
// this.addMouseListener(); // 地图鼠标移动事件
// this.addMouseClick(); // 地图鼠标左键单击事件
// this.addMouseRightClick(); // 地图鼠标右键点击事件
// this.addMouseLeftDown(); // 地图鼠标左键压下事件
window.testPath = this.drawPath(this.testPoints);
// window.testPolyline = this.drawPolyline(this.testPoints);
window.viewer = viewer;
viewer.clock.shouldAnimate = true;
},
initTimeline(points) {
let viewer = this._viewer;
if (points.length > 0) {
var start = Cesium.JulianDate.fromDate(new Date("2022-10-9"));
var stop = Cesium.JulianDate.addSeconds(
start,
points.length - 1,
new Cesium.JulianDate()
);
this.start = start;
this.stop = stop;
//Make sure viewer is at the desired time.
viewer.clock.startTime = start.clone();
viewer.clock.stopTime = stop.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
viewer.clock.multiplier = 0.06;
//Set timeline to simulation bounds
viewer.timeline.zoomTo(start, stop);
viewer.clock.shouldAnimate = true;
}
},
/**
* 根据类型绘制对象
* @param type point、polyline、polygon
*/
draw() {
//绘制点
let that = this;
let viewer = this._viewer;
let tempEntities = this.tempEntities;
let position = [];
let tempPoints = [];
// 开启深度检测
viewer.scene.globe.depthTestAgainstTerrain = true;
let handler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas
);
document.getElementsByTagName("body").item(0).style.cursor =
"crosshair";
//鼠标移动事件
handler.setInputAction(function (movement) {
let tooltip = document.getElementById("tooltip");
tooltip.style.display = "block";
tooltip.style.left = movement.endPosition.x + 15 + "px";
tooltip.style.top = movement.endPosition.y + "px";
let car3 = viewer.scene.pickPosition(movement.endPosition);
//当鼠标在一些Entity上时car3会是undefined
// if (tempPoints.length > 0 && Cesium.defined(car3)) {
// // if (!window.lineEntity || that.isAddPoint) {
// // window.lineEntity = that.drawPath([...tempPoints, car3]);
// // that.isAddPoint = false;
// // }
// // let positions = window.lineEntity.polyline.positions.getValue();
// // positions[positions.length - 1].x = car3.x;
// // positions[positions.length - 1].y = car3.y;
// // positions[positions.length - 1].z = car3.z;
// // window.lineEntity.polyline.positions =
// // new Cesium.CallbackProperty(function () {
// // return positions;
// // }, false);
// if (window.lineEntity) {
// viewer.entities.remove(window.lineEntity);
// }
// window.lineEntity = that.drawPath([...tempPoints, car3]);
// }
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
//左键点击操作
handler.setInputAction(function (click) {
that.isAddPoint = true;
//调用获取位置信息的接口
let ray = viewer.camera.getPickRay(click.position);
position = viewer.scene.globe.pick(ray, viewer.scene);
//将笛卡尔三维坐标转为地图坐标(弧度)
var cartographic =
viewer.scene.globe.ellipsoid.cartesianToCartographic(position);
var lat_String = Cesium.Math.toDegrees(
cartographic.latitude
).toFixed(6);
var log_String = Cesium.Math.toDegrees(
cartographic.longitude
).toFixed(6);
tempPoints.push([Number(log_String), Number(lat_String), 200]);
// tempPoints.push(position);
let tempLength = tempPoints.length;
//调用绘制点的接口
// let point = that.drawPoint(tempPoints[tempPoints.length - 1]);
// tempEntities.push(point);
if (tempLength > 1) {
let pointline = that.drawPath(tempPoints);
window.pointline = pointline;
window.tempPoints = tempPoints;
tempEntities.push(pointline);
} else {
// tooltip.innerHTML = "请绘制下一个点,右键结束";
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
//右键点击操作
handler.setInputAction(function (click) {
tempPoints = [];
handler.destroy(); //关闭事件句柄
handler = null;
viewer.entities.remove(window.lineEntity);
window.lineEntity = null;
let tooltip = document.getElementById("tooltip");
tooltip.style.display = "none";
document.getElementsByTagName("body").item(0).style.cursor =
"default";
}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
},
drawPoint(position, config) {
let viewer = this._viewer;
let config_ = config ? config : {};
return viewer.entities.add({
name: "点几何对象",
position: position,
point: {
color: Cesium.Color.SKYBLUE,
pixelSize: 10,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
});
},
drawPath(coords, config_) {
let viewer = this._viewer;
// 设置点的时间
Cesium.Math.setRandomNumberSeed(3);
//Set bounds of our simulation time
const start = Cesium.JulianDate.fromDate(new Date(2015, 2, 25, 16));
const stop = Cesium.JulianDate.addSeconds(
start,
coords.length - 1,
new Cesium.JulianDate()
);
//Make sure viewer is at the desired time.
viewer.clock.startTime = start.clone();
viewer.clock.stopTime = stop.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
viewer.clock.multiplier = 0.2;
//Set timeline to simulation bounds
viewer.timeline.zoomTo(start, stop);
// viewer.clock.shouldAnimate = true;
// 插值
const positionProperty = this.getPositionProperty(coords, start);
let orientation = new Cesium.VelocityOrientationProperty(
positionProperty
);
//监听时间变化,关键代码。
// viewer.clock.onTick.addEventListener(function (e) {
// if (viewer.clock.shouldAnimate === true) {
// let ori = orientation.getValue(viewer.clock.currentTime); //获取偏向角
// let center = position.getValue(viewer.clock.currentTime); //获取位置
// let transform = Cesium.Matrix4.fromRotationTranslation(
// Cesium.Matrix3.fromQuaternion(ori),
// center
// ); //将偏向角转为3*3矩阵利用实时点位转为4*4矩阵
// viewer.camera.lookAtTransform(
// transform,
// new Cesium.Cartesian3(-100, 0, 0)
// ); //将相机向后面放一点
// }
// });
return viewer.entities.add({
show: true,
//Set the entity availability to the same interval as the simulation time.
availability: new Cesium.TimeIntervalCollection([
new Cesium.TimeInterval({
start: start,
stop: stop,
}),
]),
//使用计算的位置
position: positionProperty,
//Automatically compute orientation based on position movement.
orientation: orientation,
//Load the Cesium plane model to represent the entity
model: {
show: true,
uri: "./SampleData/models/CesiumAir/Cesium_Air.glb",
minimumPixelSize: 64,
},
//Show the path as a pink line sampled in 1 second increments.
path: {
resolution: 1,
material: new Cesium.PolylineGlowMaterialProperty({
glowPower: 0.1,
color: Cesium.Color.YELLOW,
}),
width: 10,
},
});
},
getPositionProperty(coords, start) {
// 给轨迹点关联时间和插值
const property = new Cesium.SampledPositionProperty();
// property.setInterpolationOptions({
// // interpolationDegree: 5,
// // interpolationAlgorithm: Cesium.LagrangePolynomialApproximation, //设置插值算法
// interpolationDegree: 2,
// interpolationAlgorithm: Cesium.HermitePolynomialApproximation,
// });
for (var i = 0; i < coords.length; i++) {
var time = Cesium.JulianDate.addSeconds(
start,
i,
new Cesium.JulianDate()
);
var position = Cesium.Cartesian3.fromDegrees(
coords[i][0],
coords[i][1],
coords[i][2]
);
property.addSample(time, position);
this._viewer.entities.add({
position: position,
point: {
color: Cesium.Color.SKYBLUE,
pixelSize: 10,
outlineColor: Cesium.Color.YELLOW,
outlineWidth: 3,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
// heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
});
}
// this.position = property;
// this.orientation = new Cesium.VelocityOrientationProperty(property)
return property;
},
drawPolyline(coords, config_) {
let viewer = this._viewer;
let config = config_ ? config_ : {};
// 设置点的时间
Cesium.Math.setRandomNumberSeed(3);
//Set bounds of our simulation time
const start = Cesium.JulianDate.fromDate(new Date(2015, 2, 25, 16));
const stop = Cesium.JulianDate.addSeconds(
start,
coords.length - 1,
new Cesium.JulianDate()
);
//Make sure viewer is at the desired time.
viewer.clock.startTime = start.clone();
viewer.clock.stopTime = stop.clone();
viewer.clock.currentTime = start.clone();
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
viewer.clock.multiplier = 0.2;
//Set timeline to simulation bounds
viewer.timeline.zoomTo(start, stop);
// viewer.clock.shouldAnimate = true;
// 插值
const positionProperty = this.getPositionProperty(coords, start);
let orientation = new Cesium.VelocityOrientationProperty(
positionProperty
);
return viewer.entities.add({
name: "线几何对象",
availability: new Cesium.TimeIntervalCollection([
new Cesium.TimeInterval({
start: start,
stop: stop,
}),
]),
position: positionProperty,
//Automatically compute orientation based on position movement.
orientation: orientation,
polyline: {
// positions: positionProperty,
// positions: new Cesium.CallbackProperty(function () {
// return positions;
// }, false),
width: config.width ? config.width : 5.0,
material: new Cesium.PolylineGlowMaterialProperty({
color: config.color
? new Cesium.Color.fromCssColorString(config.color)
: Cesium.Color.GOLD,
}),
depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
color: config.color
? new Cesium.Color.fromCssColorString(config.color)
: Cesium.Color.GOLD,
}),
// clampToGround: true,
},
});
},
/**
* 清除实体
*/
clearDrawEntities() {
let viewer = this._viewer;
this.tempEntities = [];
// 清除之前的实体
viewer.entities.removeAll();
},
},
});
</script>
</body>
</html>