cesium.vue 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. <template>
  2. <div class="mapBox">
  3. <div id="cesiumContainer" style="width: 100%; height: 100vh"></div>
  4. <div class="menuBox" :class="allyShow ? '' : 'switch'">
  5. <div class="item">
  6. <span>图源:</span>
  7. <el-select
  8. v-model="basicMapId"
  9. size="small"
  10. style="width: 120px"
  11. @change="setMapImageryProvider"
  12. >
  13. <el-option
  14. v-for="item in basicMapList"
  15. :key="item.id"
  16. :label="item.name"
  17. :value="item.id"
  18. />
  19. </el-select>
  20. </div>
  21. <div class="item">
  22. <el-button type="primary" size="small" @click="resetViewport()"
  23. >初始化视角</el-button
  24. >
  25. </div>
  26. <div class="item">
  27. <el-button
  28. size="small"
  29. :type="windLayer ? 'danger' : 'primary'"
  30. @click="switchWindLayer"
  31. >{{ windLayer ? "关闭" : "显示" }}风场图</el-button
  32. >
  33. </div>
  34. <div class="item">
  35. <el-button
  36. size="small"
  37. :type="cloudLayer ? 'danger' : 'primary'"
  38. @click="switchCloudLayer"
  39. >{{ cloudLayer ? "关闭" : "显示" }}云图</el-button
  40. >
  41. </div>
  42. <div class="item">
  43. <el-button
  44. size="small"
  45. :type="rainLayer ? 'danger' : 'primary'"
  46. @click="switchRainLayer"
  47. >{{ rainLayer ? "关闭" : "显示" }}降雨图</el-button
  48. >
  49. </div>
  50. <div class="item">
  51. <el-button
  52. size="small"
  53. :type="rainLayer ? 'danger' : 'primary'"
  54. @click="switchTemperatureLayerr"
  55. >{{ rainLayer ? "关闭" : "显示" }}温度图</el-button
  56. >
  57. </div>
  58. <el-tooltip
  59. class="box-item"
  60. effect="dark"
  61. :content="`点击${allyShow ? '隐藏' : '常显'}菜单栏`"
  62. placement="bottom-end"
  63. >
  64. <el-icon
  65. style="margin-left: 20px"
  66. size="20px"
  67. :color="allyShow ? '#1890ff' : '#f25656'"
  68. @click="allyShow = !allyShow"
  69. >
  70. <House
  71. :style="`transform: rotate(${
  72. allyShow ? -45 : 45
  73. }deg); transition: 0.2s; cursor: pointer;`"
  74. />
  75. </el-icon>
  76. </el-tooltip>
  77. </div>
  78. <div
  79. class="tag"
  80. :style="`left:${userClickLeft}px;top:${userClickTop}px`"
  81. v-if="tagMsg || tagMsg === ''"
  82. >
  83. <el-icon class="is-loading" v-if="tagMsg === ''">
  84. <Loading />
  85. </el-icon>
  86. <span v-else>{{ tagMsg || "" }}</span>
  87. </div>
  88. <div class="devInfoBox" v-if="showDevInfoBox">
  89. <div class="item">===&nbsp;帧率与内存&nbsp;===</div>
  90. <div class="item">运行帧率:&nbsp;{{ fps }}</div>
  91. <div class="item">响应时长:&nbsp;{{ ms }}</div>
  92. <div class="item">内存占用:&nbsp;{{ jsHeapSize }}</div>
  93. <template v-if="gVendor || gRenderer">
  94. <div class="item" style="margin-top: 12px">
  95. ====&nbsp;显卡信息&nbsp;====
  96. </div>
  97. <el-tooltip
  98. effect="dark"
  99. :content="gVendor"
  100. placement="top-end"
  101. v-if="gVendor"
  102. >
  103. <div class="item">制造商:&nbsp;{{ gVendor }}</div>
  104. </el-tooltip>
  105. <el-tooltip
  106. effect="dark"
  107. :content="gRenderer"
  108. placement="top-end"
  109. v-if="gRenderer"
  110. >
  111. <div class="item">型号:&nbsp;{{ gRenderer }}</div>
  112. </el-tooltip>
  113. </template>
  114. </div>
  115. </div>
  116. <el-dialog
  117. class="modelDialog"
  118. v-model="showFjDialog"
  119. title="Tips"
  120. top="50px"
  121. width="80%"
  122. :before-close="handleClose"
  123. >
  124. <el-tabs
  125. v-model="showFjDialogActiveName"
  126. style="width: 100%"
  127. type="border-card"
  128. @tab-click="handleClick"
  129. >
  130. <el-tab-pane label="基础信息" name="jcxx">基础信息</el-tab-pane>
  131. <el-tab-pane label="视频监控" name="spjk">视频监控</el-tab-pane>
  132. <el-tab-pane label="故障查看" name="gzck">故障查看</el-tab-pane>
  133. <el-tab-pane label="模型解构" name="third">
  134. <!-- <ModelUnpack /> -->
  135. </el-tab-pane>
  136. </el-tabs>
  137. </el-dialog>
  138. </template>
  139. <script>
  140. // import * as Cesium from "../Cesium";
  141. // import "../Cesium/Widgets/widgets.css";
  142. import * as Cesium from "cesium";
  143. import "cesium/Build/Cesium/Widgets/widgets.css";
  144. import Windy from "../assets/wind/Windy_source.js";
  145. import basicGeoJson from "../assets/geoJson/basic.json";
  146. import windLineJson from "../assets/geoJson/windLine_2017121300.json";
  147. import axios from "axios";
  148. // import ModelUnpack from "@/components/modelUnpack.vue";
  149. export default {
  150. name: "CesiumMap",
  151. components: {
  152. // ModelUnpack,
  153. },
  154. data() {
  155. return {
  156. showFjDialog: false,
  157. showFjDialogActiveName: "jcxx",
  158. checkMode: false, // 调试模式
  159. allyShow: false,
  160. viewer: null,
  161. windLayer: null, // 风场图
  162. windLayerTimmer: null, // 风场图计时器
  163. cloudLayer: null, // 卫星云图
  164. rainLayer: null, // 降雨图
  165. basicMapId: "gaodeyingxiang", // 地球底图 ID
  166. // 地球底图数组
  167. basicMapList: [
  168. {
  169. id: "gaodeyingxiang",
  170. name: "高德影像地图",
  171. url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
  172. minimumLevel: 3,
  173. maximumLevel: 18,
  174. credit: "basicMap",
  175. },
  176. {
  177. id: "gaodeshiliang",
  178. name: "高德矢量地图",
  179. url: "https://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
  180. minimumLevel: 3,
  181. maximumLevel: 18,
  182. credit: "basicMap",
  183. },
  184. {
  185. id: "carto",
  186. name: "Carto地图",
  187. url: "http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png",
  188. credit: "basicMap",
  189. },
  190. ],
  191. earthLayer: [],
  192. userClickLeft: 0,
  193. userClickTop: 0,
  194. tagMsg: null,
  195. systemInfoTimmer: null,
  196. showDevInfoBox: true,
  197. fps: "", // 设备帧率
  198. ms: "", // 设备响应时间
  199. jsHeapSize: "", // 内存占用
  200. gVendor: "",
  201. gRenderer: "",
  202. labelLayer: null, // 城市名称 label 集合
  203. loadDone: false, // 地球首次加载滚动到 reset 位置是否完成
  204. };
  205. },
  206. mounted() {
  207. this.initEventListener();
  208. this.initCesium();
  209. if (this.showDevInfoBox) {
  210. this.initSystemInfo();
  211. }
  212. this.getData(106.169866, 38.46637);
  213. },
  214. unmounted() {
  215. if (this.windLayer !== null) {
  216. clearInterval(this.windLayerTimmer);
  217. this.windLayer.removeLines();
  218. this.windLayer = null;
  219. this.windLayerTimmer = null;
  220. }
  221. clearInterval(this.systemInfoTimmer);
  222. this.systemInfoTimmer = null;
  223. },
  224. methods: {
  225. getData(lat, lon) {
  226. // axios
  227. // .get(
  228. // `https://api.waqi.info/feed/geo:${lat};${lon}/?token=904a1bc6edf77c428347f2fe54cf663bcffaec21`
  229. // )
  230. // .then((res) => {
  231. // console.log(1122, res);
  232. // });
  233. },
  234. // 初始化一些监听事件
  235. initEventListener() {
  236. const mapBox = document.querySelector(".mapBox");
  237. mapBox.addEventListener("click", (e) => {
  238. const rect = mapBox.getBoundingClientRect();
  239. this.userClickLeft = (e.clientX - rect.left).toFixed(0);
  240. this.userClickTop = (e.clientY - rect.top + 20).toFixed(0);
  241. });
  242. },
  243. // 初始化地球
  244. async initCesium() {
  245. // 需要从 https://cesium.com/ion/signup 获取
  246. Cesium.Ion.defaultAccessToken =
  247. "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIwYTQwNDk3MC05YTZkLTQ2ZTEtODc0MS1lZTFkYjFlOTFmNmQiLCJpZCI6MTcyNDQ1LCJpYXQiOjE3NTQ4ODA4MzF9.KnhENYiHxNwTkhTWRA-lHqG59coLVT2FsIyOru2TV3E";
  248. // 修改 Cesium 默认地图视角为宁夏,狗东西没效果不知道为什么
  249. // Cesium.Camera.DEFAULT_VIEW_RACTANGLE = Cesium.Rectangle.fromDegrees(
  250. // 104.17,
  251. // 35.14,
  252. // 107.72,
  253. // 39.23
  254. // );
  255. const viewer = new Cesium.Viewer("cesiumContainer", {
  256. geocoder: false, // 地址搜索控件
  257. homeButton: false, // 返回地图初始位置控件
  258. infoBox: false, // 地图默认的信息控件
  259. sceneModePicker: false, // 场景模式切换控件
  260. baseLayerPicker: false, // 底图切换控件
  261. navigationHelpButton: false, // 帮助控件
  262. animation: false, // 动画控制控件
  263. timeline: false, // 时间线控件
  264. fullscreenButton: false, // 全屏按钮控件
  265. imageryProvider: false, // 是否显示 Cesium 默认地图的底图
  266. vrButton: false,
  267. selectionIndicator: false,
  268. shouldAnimate: true,
  269. // terrainProvider: await Cesium.createWorldTerrainAsync({
  270. // requestVertexNormals: true,
  271. // requestWaterMask: true,
  272. // }),
  273. // terrainProvider: new Cesium.CesiumTerrainProvider({
  274. // url: "/static/layer.json", // 对应 public/terrain-data 目录
  275. // requestVertexNormals: true, // 保留法线数据(光照效果)
  276. // requestWaterMask: false, // 本地地形通常无水面效果(需自定义)
  277. // }),
  278. });
  279. // 隐藏 Cesium Logo
  280. viewer.cesiumWidget.creditContainer.style.display = "none";
  281. this.viewer = viewer;
  282. this.setMapImageryProvider();
  283. this.initGeoJsonData();
  284. // 添加一些3D模型
  285. this.addModel(
  286. "./static/model/fjSolo/model.glb",
  287. "风机",
  288. 106.169866,
  289. 38.46637
  290. );
  291. },
  292. addModel(uri, name, lon, lat) {
  293. const hpRoll = new Cesium.HeadingPitchRoll(90.0, 0.0, 0.0);
  294. const position = Cesium.Cartesian3.fromDegrees(lon, lat);
  295. const orientation = Cesium.Transforms.headingPitchRollQuaternion(
  296. position,
  297. hpRoll
  298. );
  299. this.viewer.entities.add({
  300. name, // 模型名称
  301. position, // 模型位置
  302. orientation, // 模型朝向
  303. model: {
  304. uri,
  305. scale: 500.0,
  306. // 模型贴地
  307. heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  308. },
  309. });
  310. },
  311. // 初始化Cesium内部鼠标事件
  312. initEventInputAction() {
  313. this.$nextTick(() => {
  314. const viewer = this.viewer;
  315. // 添加点击事件显示坐标
  316. viewer.screenSpaceEventHandler.setInputAction((movement) => {
  317. const ray = this.viewer.camera.getPickRay(movement.position);
  318. if (!ray) {
  319. this.tagMsg = null;
  320. console.log("无法获取射线");
  321. return;
  322. }
  323. const position = this.viewer.scene.globe.pick(ray, this.viewer.scene);
  324. if (!position) {
  325. this.tagMsg = null;
  326. console.log("未找到地球表面交点");
  327. return;
  328. }
  329. const cartographic = Cesium.Cartographic.fromCartesian(position);
  330. if (!cartographic) {
  331. this.tagMsg = null;
  332. console.log("坐标转换失败");
  333. return;
  334. }
  335. this.getClickCloudOpacity(cartographic);
  336. this.getLocationData(cartographic);
  337. return;
  338. const cartesian = viewer.camera.pickEllipsoid(
  339. movement.position,
  340. viewer.scene.globe.ellipsoid
  341. );
  342. if (cartesian) {
  343. const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  344. const lon = Cesium.Math.toDegrees(cartographic.longitude).toFixed(
  345. 5
  346. );
  347. const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(5);
  348. viewer.entities.removeAll();
  349. viewer.entities.add({
  350. position: cartesian,
  351. point: {
  352. pixelSize: 10,
  353. color: Cesium.Color.RED,
  354. },
  355. label: {
  356. text: `经度: ${lon}°, 纬度: ${lat}°`,
  357. font: '16px "Microsoft YaHei"',
  358. fillColor: Cesium.Color.WHITE,
  359. outlineColor: Cesium.Color.BLACK,
  360. outlineWidth: 2,
  361. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  362. pixelOffset: new Cesium.Cartesian2(0, -30),
  363. },
  364. });
  365. }
  366. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  367. // 监听鼠标滚轮事件
  368. viewer.screenSpaceEventHandler.setInputAction((wheelment) => {
  369. this.tagMsg = null;
  370. }, Cesium.ScreenSpaceEventType.WHEEL);
  371. // 监听鼠标移动事件
  372. // viewer.screenSpaceEventHandler.setInputAction((movement) => {
  373. // this.getHoverCityLabel(movement);
  374. // }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  375. });
  376. },
  377. // 获取鼠标划过位置的城市名称 label
  378. getHoverCityLabel(movement) {
  379. const picked = this.viewer.scene.pick(movement.startPosition);
  380. const label = picked ? picked.primitive : null;
  381. if (label) {
  382. this.viewer.scene.canvas.style.cursor = "pointer";
  383. } else {
  384. this.viewer.scene.canvas.style.cursor = "default";
  385. }
  386. this.labelLayer._labels.forEach((ele) => {
  387. if (ele.id === label?.id) {
  388. label.fillColor = Cesium.Color.YELLOW;
  389. label.outlineColor = Cesium.Color.BLACK;
  390. } else {
  391. ele.fillColor = Cesium.Color.fromCssColorString("#000");
  392. ele.outlineColor = Cesium.Color.WHITE;
  393. }
  394. });
  395. },
  396. // 根据经纬度获取周围一定范围城市基础信息
  397. getLocationData({ latitude, longitude }) {
  398. const lat = Cesium.Math.toDegrees(latitude);
  399. const lon = Cesium.Math.toDegrees(longitude);
  400. axios
  401. .get(
  402. `/ventusky/ventusky_location.json.php?lat=${lat}&lon=${lon}&zoom=${this.getZoomLevel()}`
  403. )
  404. .then((res) => {
  405. console.log(111, res.data);
  406. // https://api.waqi.info/feed/geo:35.3286804492;108.9025100708/?token=904a1bc6edf77c428347f2fe54cf663bcffaec21
  407. // res.data.city
  408. });
  409. },
  410. // 获取 zoom 级别
  411. getZoomLevel() {
  412. let zoomLevel = 0;
  413. const tilesToRender = this.viewer.scene.globe._surface._tilesToRender;
  414. if (tilesToRender.length !== 0) {
  415. zoomLevel = tilesToRender[0].level;
  416. }
  417. return zoomLevel - 1;
  418. },
  419. // 初始化性能监控
  420. initSystemInfo() {
  421. this.viewer.scene.debugShowFramesPerSecond = false;
  422. // 性能监控变量
  423. let lastFrameTime = performance.now();
  424. let frameCount = 0;
  425. let fps = 0;
  426. let frameTime = 0;
  427. // 获取帧率与响应时长
  428. this.viewer.scene.postRender.addEventListener(() => {
  429. const now = performance.now();
  430. const delta = now - lastFrameTime;
  431. frameCount++;
  432. // 每秒更新一次数据(避免更新太频繁)
  433. if (delta >= 1000) {
  434. fps = Math.round((frameCount * 1000) / delta);
  435. frameTime = delta / frameCount;
  436. // 更新显示
  437. this.fps = `${fps} FPS`;
  438. this.ms = `${frameTime.toFixed(1) + " ms"}`;
  439. // 重置计数器
  440. frameCount = 0;
  441. lastFrameTime = now;
  442. }
  443. });
  444. // 获取内存占用
  445. if (window.performance && performance.memory) {
  446. const jsHeapSize = performance.memory.usedJSHeapSize / 1048576;
  447. this.jsHeapSize = `${parseInt(jsHeapSize)} MB`;
  448. // const memory = performance.memory;
  449. // console.log("已分配堆内存:", memory.totalJSHeapSize / 1048576 + " MB");
  450. // console.log("已使用堆内存:", memory.usedJSHeapSize / 1048576 + " MB");
  451. // console.log("堆内存限制:", memory.jsHeapSizeLimit / 1048576 + " MB");
  452. }
  453. // 获取显卡信息
  454. const canvas = document.createElement("canvas");
  455. const gl = canvas.getContext("webgl");
  456. if (gl) {
  457. const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");
  458. if (debugInfo) {
  459. const gVendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);
  460. const gRenderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
  461. // console.log("GPU厂商:", gVendor);
  462. // console.log("GPU型号:", gRenderer);
  463. this.gVendor = gVendor;
  464. this.gRenderer = gRenderer.split(",")?.[1]
  465. ? gRenderer.split(",")?.[1]
  466. : "";
  467. }
  468. }
  469. },
  470. getClickCloudOpacity(cartographic) {
  471. try {
  472. const level = this.calculateTileLevel(this.viewer);
  473. const tilingScheme = new Cesium.WebMercatorTilingScheme();
  474. // 确保 tilingScheme 有 positionToTileXY 方法
  475. if (!tilingScheme.positionToTileXY) {
  476. console.error("tilingScheme没有positionToTileXY方法");
  477. return;
  478. }
  479. if (!this.cloudLayer) {
  480. this.tagMsg = null;
  481. } else {
  482. this.tagMsg = "";
  483. }
  484. const tileXY = tilingScheme.positionToTileXY(cartographic, level);
  485. this.checkMode &&
  486. console.log(`瓦片坐标: 级别=${level}, X=${tileXY.x}, Y=${tileXY.y}`);
  487. const clickTileUrl = this.replaceTemplate(
  488. // mapSelect.url,
  489. "https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=3b66d35579770393051599f8d518df4a",
  490. level,
  491. tileXY
  492. );
  493. this.checkMode && console.log(`用户点击位置瓦片url: ${clickTileUrl}`);
  494. // 存储当前瓦片信息
  495. const layer = this.viewer.imageryLayers.get(0);
  496. const provider = layer.imageryProvider;
  497. const currentTile = {
  498. x: tileXY.x,
  499. y: tileXY.y,
  500. level: level,
  501. rectangle: tilingScheme.tileXYToRectangle(tileXY.x, tileXY.y, level),
  502. size: {
  503. width: provider.tileWidth || 256,
  504. height: provider.tileHeight || 256,
  505. },
  506. };
  507. // 计算并显示在瓦片内的位置
  508. const clickPos = this.calculateTilePosition(cartographic, currentTile);
  509. if (this.cloudLayer) {
  510. this.getTileImageOpacity(
  511. clickTileUrl,
  512. clickPos.pixelX,
  513. clickPos.pixelY
  514. ).then((imgSource) => {
  515. const {
  516. rawAlpha, // 原始透明度值 (0-255)
  517. alphaPercentage, // 透明度百分比
  518. whiteScore, // 白色程度得分 (0-100)
  519. } = imgSource;
  520. this.checkMode && console.log(111, alphaPercentage);
  521. this.tagMsg = `${alphaPercentage * 2}%`;
  522. });
  523. }
  524. if (this.checkMode) {
  525. const tileRectangle = tilingScheme.tileXYToRectangle(
  526. tileXY.x,
  527. tileXY.y,
  528. level
  529. );
  530. this.highlightTile(viewer, tileRectangle);
  531. }
  532. } catch (error) {
  533. console.error("获取瓦片时出错:", error);
  534. }
  535. },
  536. // 计算瓦片级别的辅助函数
  537. calculateTileLevel(viewer) {
  538. // 方法1:根据相机高度估算
  539. const height = viewer.camera.positionCartographic.height;
  540. if (!height) return 12; // 默认值
  541. // 高度与级别的近似关系(根据实际需求调整)
  542. const level = Math.floor(20 - Math.log(height / 1000) / Math.log(2));
  543. return Math.max(0, Math.min(18, level)); // 限制在0-18级之间
  544. // 方法2:使用当前视图的细节层次
  545. // return viewer.scene.globe.maximumScreenSpaceError;
  546. },
  547. // 高亮显示瓦片的辅助函数
  548. highlightTile(viewer, rectangle) {
  549. // 移除之前的高亮
  550. viewer.entities.removeById("highlighted-tile");
  551. // 添加新的高亮
  552. viewer.entities.add({
  553. id: "highlighted-tile",
  554. rectangle: {
  555. coordinates: rectangle,
  556. material: Cesium.Color.RED.withAlpha(0.3),
  557. outline: true,
  558. outlineColor: Cesium.Color.RED,
  559. outlineWidth: 2,
  560. },
  561. });
  562. },
  563. // 计算在瓦片内的位置
  564. calculateTilePosition(cartographic, tile) {
  565. const rect = tile.rectangle;
  566. const size = tile.size;
  567. // 计算在瓦片内的归一化位置
  568. const lonNormalized =
  569. (cartographic.longitude - rect.west) / (rect.east - rect.west);
  570. const latNormalized =
  571. (cartographic.latitude - rect.south) / (rect.north - rect.south);
  572. // 转换为像素坐标(原点在左上角)
  573. const pixelX = Math.floor(lonNormalized * size.width);
  574. const pixelY = Math.floor((1 - latNormalized) * size.height); // 翻转Y轴
  575. this.checkMode && console.log(`left:${pixelX},top:${pixelY}`);
  576. return { pixelX, pixelY };
  577. },
  578. // canvas 获取地图瓦片颜色信息
  579. async getTileImageOpacity(imageUrl, left, top) {
  580. // 1. 创建临时图像加载网络图片
  581. const img = new Image();
  582. img.crossOrigin = "Anonymous"; // 解决跨域问题
  583. img.src = imageUrl;
  584. // 2. 图片加载完成后处理
  585. await new Promise((resolve) => (img.onload = resolve));
  586. // 3. 创建Canvas并绘制图像
  587. const canvas = document.createElement("canvas");
  588. canvas.width = img.width;
  589. canvas.height = img.height;
  590. const ctx = canvas.getContext("2d");
  591. ctx.drawImage(img, 0, 0);
  592. // 4. 获取鼠标点击位置的像素数据
  593. const pixelData = ctx.getImageData(left, top, 1, 1).data;
  594. const [r, g, b, alpha] = pixelData;
  595. // 5. 计算白色程度(RGB接近255的程度)
  596. const whiteRatio = (r + g + b) / (3 * 255); // RGB平均值归一化
  597. const whiteScore = Math.round(whiteRatio * 100); // 映射到0-100
  598. // 6. 返回结果
  599. return {
  600. rawAlpha: alpha, // 原始透明度值 (0-255)
  601. alphaPercentage: Math.round((alpha / 255) * 100), // 透明度百分比
  602. whiteScore: whiteScore, // 白色程度得分 (0-100)
  603. };
  604. },
  605. // 替换底图 xyz 值为鼠标点击位置的值并返回
  606. replaceTemplate(str, level, tileXY) {
  607. return str.replace(/\{([xyz])\}/g, (match, key) => {
  608. switch (key) {
  609. case "x":
  610. return tileXY.x;
  611. case "y":
  612. return tileXY.y;
  613. case "z":
  614. return level;
  615. default:
  616. return match; // 未匹配时返回原内容(理论上不会执行)
  617. }
  618. });
  619. },
  620. // 设置地球底图
  621. setMapImageryProvider() {
  622. if (this.imageryProvider) {
  623. this.viewer.imageryLayers.remove(this.imageryProvider);
  624. this.imageryProvider = null;
  625. }
  626. const imageryProvider = this.basicMapList.find((ele) => {
  627. return ele.id === this.basicMapId;
  628. });
  629. this.imageryProvider = new Cesium.UrlTemplateImageryProvider(
  630. imageryProvider
  631. );
  632. // 添加底图
  633. this.viewer.imageryLayers.addImageryProvider(this.imageryProvider);
  634. },
  635. // 初始化 geoJson 数据
  636. async initGeoJsonData() {
  637. // 创建GeoJSON数据源
  638. await new Cesium.GeoJsonDataSource.load(basicGeoJson, {
  639. stroke: Cesium.Color.GRAY, // 边界线颜色
  640. fill: Cesium.Color.BLACK.withAlpha(0), // 填充颜色
  641. strokeWidth: 1, // 边界线宽度
  642. markerSymbol: "?", // 点要素的符号
  643. clampToGround: true, // 贴地
  644. }).then((dataSource) => {
  645. // 添加到视图
  646. this.viewer.dataSources.add(dataSource);
  647. var entities = dataSource.entities.values;
  648. for (let i = 0; i < entities.length; i++) {
  649. let entity = entities[i];
  650. entity.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
  651. //单独设置线条样式
  652. var positions = entity.polygon.hierarchy._value.positions;
  653. entity.polyline = {
  654. positions: positions,
  655. width: 1,
  656. outline: false,
  657. };
  658. }
  659. // 添加中文标签图层
  660. const labelLayer = new Cesium.LabelCollection();
  661. this.viewer.scene.primitives.add(labelLayer);
  662. const cities = [];
  663. basicGeoJson?.features?.forEach((ele) => {
  664. if (Array.isArray(ele.properties.centroid)) {
  665. const name = ele.properties.name;
  666. const lon = ele.properties.centroid[0];
  667. const lat = ele.properties.centroid[1];
  668. cities.push({ name, lon, lat });
  669. }
  670. });
  671. cities.forEach((city, index) => {
  672. labelLayer.add({
  673. id: index,
  674. name: "cityLabel",
  675. position: Cesium.Cartesian3.fromDegrees(city.lon, city.lat, 10),
  676. text: city.name,
  677. font: 'bold 14px "Microsoft YaHei", sans-serif',
  678. fillColor: Cesium.Color.fromCssColorString("#000"),
  679. outlineColor: Cesium.Color.WHITE,
  680. outlineWidth: 2,
  681. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  682. pixelOffset: new Cesium.Cartesian2(0, 0), // 设置为0
  683. horizontalOrigin: Cesium.HorizontalOrigin.CENTER, // 水平居中
  684. verticalOrigin: Cesium.VerticalOrigin.CENTER, // 垂直居中
  685. });
  686. });
  687. this.labelLayer = labelLayer;
  688. this.resetViewport();
  689. });
  690. },
  691. // 重置视角
  692. resetViewport(height = 0) {
  693. // 设置初始视图为宁夏
  694. const that = this;
  695. this.viewer.camera.flyTo({
  696. destination: Cesium.Cartesian3.fromDegrees(
  697. 106.169866,
  698. 38.46637,
  699. height || 8000000
  700. ),
  701. orientation: {
  702. heading: Cesium.Math.toRadians(0),
  703. pitch: Cesium.Math.toRadians(-90),
  704. roll: 0.0,
  705. },
  706. duration: 1.0,
  707. complete() {
  708. // 为什么要加这个?因为破库地球没完全加载完成时如果执行了监听鼠标滑动事件会光速报错滑跪
  709. if (!that.loadDone) {
  710. that.initEventInputAction();
  711. that.loadDone = true;
  712. }
  713. },
  714. });
  715. },
  716. // 添加风场图
  717. showWindLayer() {
  718. if (!this.windLayer) {
  719. this.resetViewport(20000000);
  720. this.windLayer = new Windy(windLineJson, this.viewer);
  721. this.windLayerTimmer = setInterval(() => {
  722. this.windLayer.animate();
  723. }, 200);
  724. }
  725. },
  726. // 将风向角度数据转换为矢量坐标
  727. windToVector(speed, direction) {
  728. // 转换为弧度(气象角度:0°=北风,90°=东风)
  729. const rad = Cesium.Math.toRadians(direction);
  730. // 计算UV分量(U: 东西方向,V: 南北方向)
  731. return {
  732. u: -speed * Math.sin(rad), // 东正西负
  733. v: -speed * Math.cos(rad), // 北正南负
  734. };
  735. },
  736. // 获取当前地图瓦片级别(暂时没用到怀疑有BUG)
  737. getTileLevel() {
  738. let tiles = new Set();
  739. let tilesToRender = this.viewer.scene.globe._surface._tilesToRender;
  740. if (Cesium.defined(tilesToRender)) {
  741. for (let i = 0; i < tilesToRender.length; i++) {
  742. tiles.add(tilesToRender[i].level);
  743. }
  744. return [...tiles].sort((a, b) => {
  745. return b - a;
  746. })[0];
  747. }
  748. },
  749. // 显示云图
  750. showCloudLayer() {
  751. // 设置云图位置(示例:覆盖中国区域)
  752. // const rectangle = Cesium.Rectangle.fromDegrees(
  753. // 73.66, // 西经
  754. // 18.16, // 南纬
  755. // 135.05, // 东经
  756. // 53.55 // 北纬
  757. // );
  758. // const now = new Date();
  759. // const year = now.getFullYear();
  760. // const month = String(now.getMonth() + 1).padStart(2, "0");
  761. // const day = String(now.getDate()).padStart(2, "0");
  762. // const hour = String(Math.floor(now.getHours() / 3) * 3).padStart(2, "0"); // 每3小时更新
  763. // // 创建云图图层
  764. // const cloudLayer = this.viewer.imageryLayers.addImageryProvider(
  765. // new Cesium.UrlTemplateImageryProvider({
  766. // url: `https://data.ventusky.com/${year}/${month}/${day}/icon/whole_world/hour_${hour}/icon_oblacnost_${year}${month}${day}_${hour}.jpg`,
  767. // rectangle: Cesium.Rectangle.fromDegrees(-180, -90, 180, 90),
  768. // credit: "实时卫星云图",
  769. // })
  770. // );
  771. // 调用云层底图
  772. const cloudLayer = this.viewer.imageryLayers.addImageryProvider(
  773. new Cesium.UrlTemplateImageryProvider({
  774. url: "https://tile.openweathermap.org/map/clouds_new/{z}/{x}/{y}.png?appid=3b66d35579770393051599f8d518df4a",
  775. credit: "云层影像地图",
  776. })
  777. );
  778. // 设置蓝色调效果
  779. cloudLayer.alpha = 1; // 透明度
  780. cloudLayer.brightness = 1; // 亮度
  781. cloudLayer.contrast = 1; // 对比度
  782. this.cloudLayer = cloudLayer;
  783. },
  784. // 移除风场图
  785. removeWindLayer() {
  786. if (this.windLayer) {
  787. clearInterval(this.windLayerTimmer);
  788. this.windLayer.removeLines();
  789. this.viewer.imageryLayers.remove(this.windLayer);
  790. this.windLayer = null;
  791. }
  792. },
  793. // 移除卫星云图
  794. removeCloudLayer() {
  795. if (this.cloudLayer) {
  796. this.tagMsg = null;
  797. this.viewer.imageryLayers.remove(this.cloudLayer);
  798. this.cloudLayer = null;
  799. }
  800. },
  801. // 切换风场图显隐
  802. switchWindLayer() {
  803. if (this.windLayer) {
  804. this.removeWindLayer();
  805. } else {
  806. this.showWindLayer();
  807. }
  808. },
  809. // 切换卫星云图显隐
  810. switchCloudLayer() {
  811. // this.$router.push({
  812. // path: "/cloudLayer",
  813. // });
  814. if (this.cloudLayer) {
  815. this.removeCloudLayer();
  816. } else {
  817. this.showCloudLayer();
  818. }
  819. },
  820. switchRainLayer() {
  821. this.$router.push({
  822. path: "/rainLayer",
  823. });
  824. },
  825. switchTemperatureLayerr() {
  826. this.$router.push({
  827. path: "/temperatureLayer",
  828. });
  829. },
  830. },
  831. };
  832. </script>
  833. <style lang="less" scoped>
  834. .mapBox {
  835. width: 100%;
  836. height: 100%;
  837. position: relative;
  838. box-sizing: content-box;
  839. position: relative;
  840. .menuBox {
  841. position: absolute;
  842. left: 0;
  843. top: 0;
  844. width: 100%;
  845. background: #fff;
  846. display: flex;
  847. justify-content: flex-end;
  848. align-items: center;
  849. padding: 10px;
  850. .el-button {
  851. margin: 0;
  852. }
  853. .item {
  854. font-size: 12px;
  855. margin-left: 10px;
  856. }
  857. &.switch {
  858. opacity: 0;
  859. transition: 0.2s;
  860. &:hover {
  861. opacity: 1;
  862. transition: 0.2s;
  863. }
  864. }
  865. }
  866. .tag {
  867. position: absolute;
  868. left: 0;
  869. top: 0;
  870. background: #fff;
  871. font-size: 12px;
  872. color: #000;
  873. padding: 4px 8px;
  874. border-radius: 28px;
  875. transform: translate(-50%, -50%);
  876. transition: 0.1s;
  877. pointer-events: none;
  878. }
  879. .devInfoBox {
  880. width: 130px;
  881. position: absolute;
  882. right: 0;
  883. bottom: 0;
  884. padding: 4px;
  885. font-size: 12px;
  886. color: #fff;
  887. background: rgba(0, 0, 0, 0.25);
  888. display: flex;
  889. flex-direction: column;
  890. justify-content: flex-start;
  891. align-items: flex-start;
  892. z-index: 500;
  893. user-select: none;
  894. .item {
  895. width: 100%;
  896. margin-top: 4px;
  897. overflow: hidden;
  898. text-overflow: ellipsis;
  899. white-space: nowrap;
  900. }
  901. }
  902. }
  903. </style>
  904. <style lang="less">
  905. .modelDialog {
  906. .el-dialog__body {
  907. height: 750px;
  908. .el-tabs {
  909. height: 100%;
  910. .el-tabs__content {
  911. height: 100%;
  912. }
  913. }
  914. }
  915. }
  916. </style>