当前位置:   article > 正文

Cesium.js基础使用(vue)

cesium.js

如何通过Cesium创建一个地图:

1、npm安装(这里使用1.95.0版本)

  1. npm i cesium@1.95.0 -s
  2. yarn add cesium@1.95.0 -s

2、组件引入

import * as Cesium from "cesium/Cesium";

3、容器创建

<div id="cesiumContainer" />

4、核心类Viewer创建

在Cesium中Viewer是一切的开端,通过newCesium.Viewer(container, options)来创建一个Viewer对象,可以把该对象理解为三维虚拟地球,在Viewer对象上的所有操作,可以看作是对三维虚拟地球的操作。

  1. const viewer = new Viewer("cesiumContainer", {
  2. infoBox: false,
  3. animation: false, // 是否显示动画控件
  4. homeButton: false, // 是否显示home键
  5. geocoder: false, // 是否显示地名查找控件
  6. baseLayerPicker: false, // 是否显示图层选择控件
  7. timeline: false, // 是否显示时间线控件
  8. fullscreenButton: false, // 是否全屏显示
  9. infoBox: false, // 是否显示点击要素之后显示的信息
  10. sceneModePicker: false, // 是否显示投影方式控件 三维/二维
  11. navigationInstructionsInitiallyVisible: false,
  12. navigationHelpButton: false, // 是否显示帮助信息控件
  13. orderIndependentTranslucency: false,
  14. shouldAnimate: true,
  15. scene3DOnly: false, // 每个几何实例将只能以3D渲染以节省GPU内存
  16. selectionIndicator: false, // 取消点击有绿框
  17. // imageryProvider: false, // 不提供地图
  18. baseLayerPicker: true, //是否显示图层选择控件
  19. });

5、 设置初始位置(经纬度、缩放比例)

  1. viewer.camera.flyTo({
  2. destination: Cesium.Cartesian3.fromDegrees(
  3. 113.764043,
  4. 34.005325,
  5. 8000000
  6. ),
  7. });

此时,一个地球就出现了!!!

cesium内置了一些图层供我们切换。

 还可以通过一些json数据给地图添加想要的区块图层

  1. //阿里云地理信息工具 数据获取
  2. viewer.dataSources.add(
  3. Cesium.GeoJsonDataSource.load(
  4. "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json"
  5. )
  6. );
我们还可以通过cesium对一些建筑物进行观察

但需要申请Cesium的令牌(token)

如何申请?

通过以下官网地址申请

 Cesium ion

 使用:

 Cesium.Ion.defaultAccessToken =       "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDVhMjQ0Yi05MDg4LTRlNDYtYTIxMi00YmI4ZWYxOWMyNTgiLCJpZCI6MTQ5MzYwLCJpYXQiOjE2ODc3ODQ0OTh9.KlhT_LCnsEtYyawpEmJ_wx44_qTUbgze-SxGMRavbAM";

之后就可以访问高清页面;

完整代码

  1. <template>
  2. <div id="cesiumContainer" @dragover="allowDrop" @drop="drop">
  3. <nav>
  4. <button @click="draw('point')">点绘制</button>
  5. <button @click="draw('polyline')">线绘制</button>
  6. <button @click="draw('polygon')">圆绘制</button>
  7. <button @click="clearDrawEntities">清空</button>
  8. </nav>
  9. </div>
  10. </template>
  11. <script>
  12. import * as Cesium from "cesium/Cesium";
  13. import { Viewer } from "cesium/Cesium";
  14. import Map from "ol/Map";
  15. import View from "ol/View";
  16. import TileLayer from "ol/layer/Tile";
  17. import XYZ from "ol/source/XYZ";
  18. import { transform, getTransform } from "ol/proj";
  19. // import { selectNodesForSpecifiedRegion } from "../../utils/gis/commonMethods";
  20. export default {
  21. name: "cesiumView",
  22. data() {
  23. return {
  24. // map: null,
  25. cesiumContainer: null,
  26. mapViewer: null,
  27. tempEntities: [],
  28. activeNames: [],
  29. };
  30. },
  31. mounted() {
  32. this.initMap();
  33. },
  34. methods: {
  35. handleChange() {},
  36. //init
  37. initMap() {
  38. // 此应用程序正在使用 Cesium 的默认 ion 访问令牌,请在使用 Ceisum API 调用之前先注册一个你自己的 Cesium ion 访问令牌
  39. Cesium.Ion.defaultAccessToken =
  40. "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJmNDVhMjQ0Yi05MDg4LTRlNDYtYTIxMi00YmI4ZWYxOWMyNTgiLCJpZCI6MTQ5MzYwLCJpYXQiOjE2ODc3ODQ0OTh9.KlhT_LCnsEtYyawpEmJ_wx44_qTUbgze-SxGMRavbAM";
  41. const viewer = new Viewer("cesiumContainer", {
  42. infoBox: false,
  43. animation: false, // 是否显示动画控件
  44. homeButton: false, // 是否显示home键
  45. geocoder: false, // 是否显示地名查找控件
  46. baseLayerPicker: false, // 是否显示图层选择控件
  47. timeline: false, // 是否显示时间线控件
  48. fullscreenButton: false, // 是否全屏显示
  49. infoBox: false, // 是否显示点击要素之后显示的信息
  50. sceneModePicker: false, // 是否显示投影方式控件 三维/二维
  51. navigationInstructionsInitiallyVisible: false,
  52. navigationHelpButton: false, // 是否显示帮助信息控件
  53. orderIndependentTranslucency: false,
  54. shouldAnimate: true,
  55. scene3DOnly: false, // 每个几何实例将只能以3D渲染以节省GPU内存
  56. selectionIndicator: false, // 取消点击有绿框
  57. // imageryProvider: false, // 不提供地图
  58. baseLayerPicker: true, //是否显示图层选择控件
  59. });
  60. //设置初始位置
  61. viewer.camera.flyTo({
  62. destination: Cesium.Cartesian3.fromDegrees(
  63. 113.764043,
  64. 34.005325,
  65. 3000
  66. ),
  67. });
  68. // entities 默认点位
  69. // const entity = viewer.entities.add({
  70. // position: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 400),
  71. // point: {
  72. // pixelSize: 50,
  73. // color: new Cesium.Color(0, 1, 0, 1),
  74. // },
  75. // });
  76. // //将摄像头设置到远点处
  77. // viewer.trackedEntity = entity;
  78. //阿里云地理信息工具 数据获取
  79. // viewer.dataSources.add(
  80. // Cesium.GeoJsonDataSource.load(
  81. // "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json"
  82. // )
  83. // );
  84. // Viewer.scene.globe.show = false;
  85. // logo去除
  86. viewer.cesiumWidget.creditContainer.style.display = "none";
  87. this.mapViewer = viewer;
  88. window.viewer = viewer;
  89. console.log(viewer, "viewer");
  90. },
  91. // deleteRectangle() {},
  92. //获取经纬度
  93. getPosition(viewer) {
  94. let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  95. handler.setInputAction(function (event) {
  96. let cartesian = viewer.scene.pickPosition(event.position);
  97. let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  98. let lng = Cesium.Math.toDegrees(cartographic.longitude); // 经度
  99. let lat = Cesium.Math.toDegrees(cartographic.latitude); // 纬度
  100. let alt = cartographic.height; // 高度
  101. let coordinate = {
  102. longitude: Number(lng.toFixed(6)),
  103. latitude: Number(lat.toFixed(6)),
  104. altitude: Number(alt.toFixed(2)),
  105. };
  106. console.log(coordinate,'coordinate');
  107. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  108. },
  109. /**
  110. * Role map drop
  111. * Desc 元素拖入地图放置事件
  112. */
  113. drop(e) {
  114. e.preventDefault();
  115. this.getPosition(window.viewer);
  116. // console.log(e, "eeeeeeeeee");
  117. // const pos = transform(this.map.getEventCoordinate(e), "EPSG:3857", "EPSG:4326");
  118. // console.log(pos, "pos");
  119. // const pos = ol.proj.transform(pos, 'EPSG:3857', 'EPSG:4326');
  120. // const data = e.dataTransfer.getData("Text");
  121. // console.log(data,'data')
  122. },
  123. //图标拖动效果
  124. drag(event, item) {
  125. console.log(event, item, "---------------");
  126. },
  127. /**
  128. * Role dragover
  129. * Desc 在可拖动的元素或者被选择的文本被拖进一个有效的放置目标时(每几百毫秒)触发,
  130. * 允许元素拖入地图
  131. */
  132. allowDrop(e) {
  133. e.preventDefault();
  134. // event.preventDefault
  135. },
  136. draw(type) {
  137. //点绘制
  138. let _this = this;
  139. let viewer = this.mapViewer;
  140. let tempEntities = this.tempEntities;
  141. let position = [];
  142. let tempPoints = [];
  143. /**
  144. * Role depthTestAgainstTerrain 开启地形深度检测
  145. * desc 开启地形检测后,会计算其他地理要素和地形之间的遮挡关系。未开启时,将会出现场景变化时,地物位置显示不正确。
  146. */
  147. viewer.scene.globe.depthTestAgainstTerrain = true;
  148. /**
  149. * Role ScreenSpaceEventHandler
  150. * type => canvas
  151. * default => Document
  152. * desc 处理用户输入事件。可以添加自定义功能以在以下位置执行当用户输入输入时。
  153. */
  154. let handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  155. switch (type) {
  156. case "point":
  157. //监听 鼠标左键
  158. handler.setInputAction(function (movement) {
  159. // 从相机位置通过windowPosition 世界坐标中的像素创建一条射线。返回Cartesian3射线的位置和方向。
  160. let ray = viewer.camera.getPickRay(movement.position);
  161. // 查找射线与渲染的地球表面之间的交点。射线必须以世界坐标给出。返回Cartesian3对象
  162. position = viewer.scene.globe.pick(ray, viewer.scene);
  163. let point = _this.drawPoint(position);
  164. tempEntities.push(point);
  165. /**
  166. * Role ScreenSpaceEventType
  167. * Desc 此枚举类型用于对鼠标事件进行分类:向下,向上,单击,双击,按住按钮时移动。
  168. */
  169. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  170. // 左键双击停止绘制
  171. handler.setInputAction(function () {
  172. handler.destroy(); //关闭事件句柄
  173. handler = null;
  174. }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  175. // 右击单击停止绘制
  176. handler.setInputAction(function () {
  177. handler.destroy(); //关闭事件句柄
  178. handler = null;
  179. }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  180. break;
  181. case "polyline":
  182. //鼠标移动事件
  183. handler.setInputAction(function (movement) {},
  184. Cesium.ScreenSpaceEventType.MIDDLE_CLICK);
  185. //左键点击操作
  186. handler.setInputAction(function (click) {
  187. //调用获取位置信息的接口
  188. let ray = viewer.camera.getPickRay(click.position);
  189. position = viewer.scene.globe.pick(ray, viewer.scene);
  190. tempPoints.push(position);
  191. let tempLength = tempPoints.length;
  192. //调用绘制点的接口
  193. let point = _this.drawPoint(tempPoints[tempPoints.length - 1]);
  194. tempEntities.push(point);
  195. if (tempLength > 1) {
  196. let pointline = _this.drawPolyline([
  197. tempPoints[tempPoints.length - 2],
  198. tempPoints[tempPoints.length - 1],
  199. ]);
  200. tempEntities.push(pointline);
  201. } else {
  202. // tooltip.innerHTML = "请绘制下一个点,右键结束";
  203. }
  204. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  205. //右键点击操作
  206. handler.setInputAction(function (click) {
  207. tempPoints = [];
  208. handler.destroy(); //关闭事件句柄
  209. handler = null;
  210. }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  211. break;
  212. case "polygon":
  213. //鼠标移动事件
  214. handler.setInputAction(function (movement) {},
  215. Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  216. //左键点击操作
  217. handler.setInputAction(function (click) {
  218. //调用获取位置信息的接口
  219. let ray = viewer.camera.getPickRay(click.position);
  220. position = viewer.scene.globe.pick(ray, viewer.scene);
  221. tempPoints.push(position);
  222. let tempLength = tempPoints.length;
  223. //调用绘制点的接口
  224. let point = _this.drawPoint(position);
  225. tempEntities.push(point);
  226. if (tempLength > 1) {
  227. let pointline = _this.drawPolyline([
  228. tempPoints[tempPoints.length - 2],
  229. tempPoints[tempPoints.length - 1],
  230. ]);
  231. tempEntities.push(pointline);
  232. } else {
  233. // tooltip.innerHTML = "请绘制下一个点,右键结束";
  234. }
  235. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  236. //右键点击操作
  237. handler.setInputAction(function (click) {
  238. let cartesian = viewer.camera.pickEllipsoid(
  239. click.position,
  240. viewer.scene.globe.ellipsoid
  241. );
  242. if (cartesian) {
  243. let tempLength = tempPoints.length;
  244. if (tempLength < 3) {
  245. alert("请选择3个以上的点再执行闭合操作命令");
  246. } else {
  247. //闭合最后一条线
  248. let pointline = _this.drawPolyline([
  249. tempPoints[tempPoints.length - 1],
  250. tempPoints[0],
  251. ]);
  252. tempEntities.push(pointline);
  253. _this.drawPolygon(tempPoints);
  254. tempEntities.push(tempPoints);
  255. handler.destroy(); //关闭事件句柄
  256. handler = null;
  257. }
  258. }
  259. }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  260. break;
  261. }
  262. },
  263. drawPoint(position, config) {
  264. let viewer = this.mapViewer;
  265. let config_ = config ? config : {};
  266. return viewer.entities.add({
  267. name: "点几何对象",
  268. position: position,
  269. point: {
  270. color: Cesium.Color.SKYBLUE,
  271. pixelSize: 10,
  272. outlineColor: Cesium.Color.YELLOW,
  273. outlineWidth: 3,
  274. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  275. heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  276. },
  277. });
  278. },
  279. drawPolyline(positions, config_) {
  280. let viewer = this.mapViewer;
  281. if (positions.length < 1) return;
  282. let config = config_ ? config_ : {};
  283. return viewer.entities.add({
  284. name: "线几何对象",
  285. polyline: {
  286. positions: positions,
  287. width: config.width ? config.width : 5.0,
  288. material: new Cesium.PolylineGlowMaterialProperty({
  289. color: config.color
  290. ? new Cesium.Color.fromCssColorString(config.color)
  291. : Cesium.Color.GOLD,
  292. }),
  293. depthFailMaterial: new Cesium.PolylineGlowMaterialProperty({
  294. color: config.color
  295. ? new Cesium.Color.fromCssColorString(config.color)
  296. : Cesium.Color.GOLD,
  297. }),
  298. clampToGround: true,
  299. },
  300. });
  301. },
  302. drawPolygon(positions, config_) {
  303. let viewer = this.mapViewer;
  304. if (positions.length < 2) return;
  305. let config = config_ ? config_ : {};
  306. return viewer.entities.add({
  307. name: "面几何对象",
  308. polygon: {
  309. hierarchy: positions,
  310. material: config.color
  311. ? new Cesium.Color.fromCssColorString(config.color).withAlpha(0.2)
  312. : new Cesium.Color.fromCssColorString("#FFD700").withAlpha(0.2),
  313. },
  314. });
  315. },
  316. //清除实体
  317. clearDrawEntities() {
  318. let viewer = this.mapViewer;
  319. this.tempEntities = [];
  320. // 清除之前的实体
  321. const entitys = viewer.entities._entities._array;
  322. let length = entitys.length;
  323. // 倒叙遍历防止实体减少之后entitys[f]不存在
  324. for (let f = length - 1; f >= 0; f--) {
  325. if (
  326. entitys[f]._name &&
  327. (entitys[f]._name === "点几何对象" ||
  328. entitys[f]._name === "线几何对象" ||
  329. entitys[f]._name === "面几何对象")
  330. ) {
  331. viewer.entities.remove(entitys[f]);
  332. }
  333. }
  334. },
  335. },
  336. };
  337. </script>
  338. <style lang="less" scoped>
  339. #cesiumContainer {
  340. width: 100vw;
  341. height: 100vh;
  342. position: relative;
  343. header {
  344. position: absolute;
  345. top: 0;
  346. width: 100%;
  347. height: 50px;
  348. background: rgba(0, 0, 0, 0.5);
  349. }
  350. .leftBar {
  351. width: 250px;
  352. height: 50%;
  353. position: absolute;
  354. top: 30%;
  355. z-index: 999;
  356. .el-collapse-item__content {
  357. display: flex;
  358. justify-content: space-between;
  359. // flex-wrap: wrap;
  360. }
  361. .collapseItems {
  362. // display: block;
  363. width: 100%;
  364. height: auto;
  365. .ivu-icon {
  366. display: block;
  367. }
  368. b {
  369. display: block;
  370. text-align: center;
  371. }
  372. }
  373. }
  374. nav {
  375. position: absolute;
  376. left: 20px;
  377. top: 20px;
  378. width: 150px;
  379. height: 180px;
  380. // background: rgba(0, 0, 0, 0.5);
  381. z-index: 999;
  382. display: flex;
  383. flex-direction: column;
  384. justify-content: space-between;
  385. button {
  386. width: 100%;
  387. height: 30px;
  388. cursor: pointer;
  389. }
  390. }
  391. }
  392. </style>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/877532
推荐阅读
相关标签
  

闽ICP备14008679号