您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /**
  2. * @Author: Caven
  3. * @Date: 2019-12-27 17:13:24
  4. */
  5. import { Cesium } from '@dc-modules/namespace'
  6. import Parse from '@dc-modules/parse/Parse'
  7. import {
  8. LayerGroupEventType,
  9. LayerEventType,
  10. MouseEvent,
  11. ViewerEvent,
  12. SceneEvent
  13. } from '@dc-modules/event'
  14. import { ViewerOption, CameraOption } from '@dc-modules/option'
  15. import { Util, DomUtil } from '@dc-modules/utils'
  16. import { Transform } from '@dc-modules/transform'
  17. import createWidgets from '@dc-modules/widget'
  18. const DEF_OPTS = {
  19. animation: false, //Whether to create animated widgets, lower left corner of the meter
  20. baseLayerPicker: false, //Whether to display the layer selector
  21. imageryProvider: false, // Whether to display the default imagery
  22. fullscreenButton: false, //Whether to display the full-screen button
  23. geocoder: false, //To display the geocoder widget, query the button in the upper right corner
  24. homeButton: false, //Whether to display the Home button
  25. infoBox: false, //Whether to display the information box
  26. sceneModePicker: false, //Whether to display 3D/2D selector
  27. selectionIndicator: false, //Whether to display the selection indicator component
  28. timeline: false, //Whether to display the timeline
  29. navigationHelpButton: false, //Whether to display the help button in the upper right corner
  30. navigationInstructionsInitiallyVisible: false,
  31. creditContainer: undefined,
  32. shouldAnimate: true
  33. }
  34. class Viewer {
  35. constructor(id, options = {}) {
  36. if (!id || (typeof id === 'string' && !document.getElementById(id))) {
  37. throw new Error('Viewer:the id is empty')
  38. }
  39. this._delegate = new Cesium.Viewer(id, {
  40. ...DEF_OPTS,
  41. ...options
  42. }) // Initialize the viewer
  43. /**
  44. * Registers events
  45. */
  46. new MouseEvent(this) // Register global mouse events
  47. this._viewerEvent = new ViewerEvent() // Register viewer events
  48. this._sceneEvent = new SceneEvent(this) // Register scene events
  49. this._viewerOption = new ViewerOption(this) // Initialize the viewer option
  50. this._cameraOption = new CameraOption(this) // Initialize the camera option
  51. this._dcContainer = DomUtil.create(
  52. 'div',
  53. 'dc-container',
  54. typeof id === 'string' ? document.getElementById(id) : id
  55. ) //Register the custom container
  56. this._baseLayerPicker = new Cesium.BaseLayerPickerViewModel({
  57. globe: this._delegate.scene.globe
  58. }) //Initialize the baseLayer picker
  59. this._layerGroupCache = {}
  60. this._layerCache = {}
  61. /**
  62. * Registers default widgets
  63. */
  64. let widgets = createWidgets()
  65. Object.keys(widgets).forEach(key => {
  66. this.use(widgets[key])
  67. })
  68. }
  69. get delegate() {
  70. return this._delegate
  71. }
  72. get dcContainer() {
  73. return this._dcContainer
  74. }
  75. get scene() {
  76. return this._delegate.scene
  77. }
  78. get camera() {
  79. return this._delegate.camera
  80. }
  81. get canvas() {
  82. return this._delegate.scene.canvas
  83. }
  84. get dataSources() {
  85. return this._delegate.dataSources
  86. }
  87. get imageryLayers() {
  88. return this._delegate.imageryLayers
  89. }
  90. get terrainProvider() {
  91. return this._delegate.terrainProvider
  92. }
  93. get entities() {
  94. return this._delegate.entities
  95. }
  96. get postProcessStages() {
  97. return this._delegate.scene.postProcessStages
  98. }
  99. get clock() {
  100. return this._delegate.clock
  101. }
  102. get viewerEvent() {
  103. return this._viewerEvent
  104. }
  105. get cameraPosition() {
  106. let position = Transform.transformCartesianToWGS84(this.camera.positionWC)
  107. if (position) {
  108. position.heading = Cesium.Math.toDegrees(this.camera.heading)
  109. position.pitch = Cesium.Math.toDegrees(this.camera.pitch)
  110. position.roll = Cesium.Math.toDegrees(this.camera.roll)
  111. }
  112. return position
  113. }
  114. get resolution() {
  115. let width = this.scene.canvas.width
  116. let height = this.scene.canvas.height
  117. let min = Transform.transformWindowToWGS84(
  118. new Cesium.Cartesian2((width / 2) | 0, height - 1),
  119. this
  120. )
  121. let max = Transform.transformWindowToWGS84(
  122. new Cesium.Cartesian2((1 + width / 2) | 0, height - 1),
  123. this
  124. )
  125. if (!min || !max) {
  126. return 1
  127. }
  128. return Math.abs(min.lng - max.lng)
  129. }
  130. get viewBounds() {
  131. let width = this.scene.canvas.width
  132. let height = this.scene.canvas.height
  133. let min = Transform.transformWindowToWGS84(
  134. new Cesium.Cartesian2(0, height),
  135. this
  136. )
  137. let max = Transform.transformWindowToWGS84(
  138. new Cesium.Cartesian2(width, 0),
  139. this
  140. )
  141. if (!min || !max) {
  142. return Cesium.Rectangle.MAX_VALUE
  143. }
  144. return Cesium.Rectangle.fromDegrees(min.lng, min.lat, max.lng, max.lat)
  145. }
  146. /***
  147. *
  148. * @param layerGroup
  149. * @private
  150. */
  151. _addLayerGroup(layerGroup) {
  152. if (
  153. layerGroup &&
  154. layerGroup.layerGroupEvent &&
  155. !Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  156. ) {
  157. layerGroup.layerGroupEvent.fire(LayerGroupEventType.ADD, this)
  158. this._layerGroupCache[layerGroup.id] = layerGroup
  159. }
  160. }
  161. /**
  162. *
  163. * @param layerGroup
  164. * @private
  165. */
  166. _removeLayerGroup(layerGroup) {
  167. if (
  168. layerGroup &&
  169. layerGroup.layerGroupEvent &&
  170. Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  171. ) {
  172. layerGroup.layerGroupEvent.fire(LayerGroupEventType.REMOVE, this)
  173. delete this._layerGroupCache[layerGroup.id]
  174. }
  175. }
  176. /**
  177. * @param layer
  178. * @private
  179. */
  180. _addLayer(layer) {
  181. if (layer && layer.layerEvent) {
  182. !this._layerCache[layer.type] && (this._layerCache[layer.type] = {})
  183. if (!Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)) {
  184. layer.layerEvent.fire(LayerEventType.ADD, this)
  185. this._layerCache[layer.type][layer.id] = layer
  186. }
  187. }
  188. }
  189. /**
  190. * @param layer
  191. * @private
  192. */
  193. _removeLayer(layer) {
  194. if (
  195. layer &&
  196. layer.layerEvent &&
  197. Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)
  198. ) {
  199. layer.layerEvent.fire(LayerEventType.REMOVE, this)
  200. delete this._layerCache[layer.type][layer.id]
  201. }
  202. }
  203. /**
  204. * Sets viewer options
  205. * @param options
  206. * @returns {Viewer}
  207. */
  208. setOptions(options) {
  209. this._viewerOption.setOptions(options)
  210. return this
  211. }
  212. /**
  213. * Sets camera pitch range
  214. * @param min
  215. * @param max
  216. * @returns {Viewer}
  217. */
  218. setPitchRange(min = -90, max = -20) {
  219. this._cameraOption.setPitchRange(min, max)
  220. return this
  221. }
  222. /**
  223. * @param west
  224. * @param south
  225. * @param east
  226. * @param north
  227. * @returns {Viewer}
  228. */
  229. setBounds(west, south, east, north) {
  230. this._cameraOption.setBounds(west, south, east, north)
  231. return this
  232. }
  233. /**
  234. * Changes Scene Mode,2:2D,2.5:2.5D,3:3D
  235. * @param sceneMode
  236. * @param duration
  237. * @returns {Viewer}
  238. */
  239. changeSceneMode(sceneMode, duration = 0) {
  240. if (sceneMode === 2) {
  241. this._delegate.scene.morphTo2D(duration)
  242. } else if (sceneMode === 3) {
  243. this._delegate.scene.morphTo3D(duration)
  244. } else if (sceneMode === 2.5) {
  245. this._delegate.scene.morphToColumbusView(duration)
  246. }
  247. return this
  248. }
  249. /**
  250. * Changes Mouse Mode,0:Default,1: Change the tiltEventTypes to CameraEventType.RIGHT_DRAG
  251. * @param mouseMode
  252. * @returns {Viewer}
  253. */
  254. changeMouseMode(mouseMode) {
  255. this._cameraOption.changeMouseMode(mouseMode)
  256. return this
  257. }
  258. /**
  259. * Adds the baseLayer .
  260. * The baseLayer can be a single or an array,
  261. * and when the baseLayer is an array, the baseLayer will be loaded together
  262. * @param baseLayers
  263. * @param options
  264. * @returns {Viewer}
  265. */
  266. addBaseLayer(baseLayers, options = {}) {
  267. if (!baseLayers) {
  268. return this
  269. }
  270. this._baseLayerPicker.imageryProviderViewModels.push(
  271. new Cesium.ProviderViewModel({
  272. name: options.name || '地图',
  273. creationFunction: () => {
  274. return baseLayers
  275. }
  276. })
  277. )
  278. if (!this._baseLayerPicker.selectedImagery) {
  279. this._baseLayerPicker.selectedImagery = this._baseLayerPicker.imageryProviderViewModels[0]
  280. }
  281. this.mapSwitch && this.mapSwitch.addMap(options)
  282. return this
  283. }
  284. /**
  285. * Changes the current globe display of the baseLayer
  286. * @param index
  287. * @returns {Viewer}
  288. */
  289. changeBaseLayer(index) {
  290. if (this._baseLayerPicker && index >= 0) {
  291. this._baseLayerPicker.selectedImagery = this._baseLayerPicker.imageryProviderViewModels[
  292. index
  293. ]
  294. }
  295. return this
  296. }
  297. /**
  298. * Adds the terrain
  299. * @param terrain
  300. * @returns {Viewer}
  301. */
  302. addTerrain(terrain, param = {}) {
  303. if (!terrain) {
  304. return this
  305. }
  306. let { name = '地形' } = param
  307. this._baseLayerPicker.terrainProviderViewModels.push(
  308. new Cesium.ProviderViewModel({
  309. name,
  310. creationFunction: () => {
  311. return terrain
  312. }
  313. })
  314. )
  315. if (!this._baseLayerPicker.selectedTerrain) {
  316. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[0]
  317. }
  318. return this
  319. }
  320. /**
  321. * Changes the current globe display of the terrain
  322. * @param index
  323. * @returns {Viewer}
  324. */
  325. changeTerrain(index) {
  326. if (this._baseLayerPicker && index >= 0) {
  327. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[
  328. index
  329. ]
  330. }
  331. return this
  332. }
  333. /**
  334. * Removes terrain
  335. * @returns {Viewer}
  336. */
  337. removeTerrain() {
  338. this._baseLayerPicker.terrainProviderViewModels = []
  339. this._baseLayerPicker.selectedTerrain = undefined
  340. this._delegate.terrainProvider = new Cesium.EllipsoidTerrainProvider()
  341. return this
  342. }
  343. /**
  344. *
  345. * @param layerGroup
  346. * @returns {Viewer}
  347. */
  348. addLayerGroup(layerGroup) {
  349. this._addLayerGroup(layerGroup)
  350. return this
  351. }
  352. /**
  353. *
  354. * @param layerGroup
  355. * @returns {Viewer}
  356. */
  357. removeLayerGroup(layerGroup) {
  358. this._removeLayerGroup(layerGroup)
  359. return this
  360. }
  361. /**
  362. * add a layer
  363. * @param layer
  364. * @returns {Viewer}
  365. */
  366. addLayer(layer) {
  367. this._addLayer(layer)
  368. return this
  369. }
  370. /**
  371. * Removes a layer
  372. * @param layer
  373. * @returns {Viewer}
  374. */
  375. removeLayer(layer) {
  376. this._removeLayer(layer)
  377. return this
  378. }
  379. /**
  380. * Checks to see if the layer is included
  381. * @param layer
  382. * @returns {boolean}
  383. */
  384. hasLayer(layer) {
  385. return (
  386. layer &&
  387. layer.layerEvent &&
  388. Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)
  389. )
  390. }
  391. /**
  392. * Returns a layer by id
  393. * @param id
  394. * @returns {*|undefined}
  395. */
  396. getLayer(id) {
  397. let filters = this.getLayers().filter(item => item.id === id)
  398. return filters && filters.length ? filters[0] : undefined
  399. }
  400. /**
  401. * Returns all layers
  402. * @returns {[]}
  403. */
  404. getLayers() {
  405. let result = []
  406. Object.keys(this._layerCache).forEach(type => {
  407. let cache = this._layerCache[type]
  408. Object.keys(cache).forEach(layerId => {
  409. result.push(cache[layerId])
  410. })
  411. })
  412. return result
  413. }
  414. /**
  415. * Iterate through each layer and pass it as an argument to the callback function
  416. * @param method
  417. * @param context
  418. * @returns {Viewer}
  419. */
  420. eachLayer(method, context) {
  421. Object.keys(this._layerCache).forEach(type => {
  422. let cache = this._layerCache[type]
  423. Object.keys(cache).forEach(layerId => {
  424. method.call(context, cache[layerId])
  425. })
  426. })
  427. return this
  428. }
  429. /**
  430. * @param target
  431. * @param duration
  432. * @returns {Viewer}
  433. */
  434. flyTo(target, duration) {
  435. this._delegate.flyTo(target?.delegate || target, {
  436. duration
  437. })
  438. return this
  439. }
  440. /**
  441. * @param target
  442. * @returns {Viewer}
  443. */
  444. zoomTo(target) {
  445. this._delegate.zoomTo(target?.delegate || target)
  446. return this
  447. }
  448. /**
  449. * Camera fly to a position
  450. * @param position
  451. * @param completeCallback
  452. * @param duration
  453. * @returns {Viewer}
  454. */
  455. flyToPosition(position, completeCallback, duration) {
  456. position = Parse.parsePosition(position)
  457. this.camera.flyTo({
  458. destination: Transform.transformWGS84ToCartesian(position),
  459. orientation: {
  460. heading: Cesium.Math.toRadians(position.heading),
  461. pitch: Cesium.Math.toRadians(position.pitch),
  462. roll: Cesium.Math.toRadians(position.roll)
  463. },
  464. complete: completeCallback,
  465. duration: duration
  466. })
  467. return this
  468. }
  469. /**
  470. * Camera zoom to a position
  471. * @param position
  472. * @param completeCallback
  473. * @returns {Viewer}
  474. */
  475. zoomToPosition(position, completeCallback) {
  476. this.flyToPosition(position, completeCallback, 0)
  477. return this
  478. }
  479. /**
  480. *
  481. * @param type
  482. * @param callback
  483. * @param context
  484. * @returns {Viewer}
  485. */
  486. on(type, callback, context) {
  487. this._viewerEvent.on(type, callback, context || this)
  488. this._sceneEvent.on(type, callback, context || this)
  489. return this
  490. }
  491. /**
  492. *
  493. * @param type
  494. * @param callback
  495. * @param context
  496. * @returns {Viewer}
  497. */
  498. once(type, callback, context) {
  499. this._viewerEvent.once(type, callback, context || this)
  500. return this
  501. }
  502. /**
  503. *
  504. * @param type
  505. * @param callback
  506. * @param context
  507. * @returns {Viewer}
  508. */
  509. off(type, callback, context) {
  510. this._viewerEvent.off(type, callback, context || this)
  511. this._sceneEvent.off(type, callback, context || this)
  512. return this
  513. }
  514. /**
  515. * Destroys the viewer.
  516. */
  517. destroy() {
  518. Object.keys(this._layerCache).forEach(type => {
  519. let cache = this._layerCache[type]
  520. Object.keys(cache).forEach(layerId => {
  521. this._removeLayer(cache[layerId])
  522. })
  523. })
  524. this._delegate.destroy()
  525. this._delegate = undefined
  526. this._baseLayerPicker = undefined
  527. this._layerCache = {}
  528. this._dcContainer.parentNode.removeChild(this._dcContainer)
  529. this._dcContainer = undefined
  530. return this
  531. }
  532. /**
  533. * Export scene to image
  534. * @param name
  535. * @returns {Viewer}
  536. */
  537. exportScene(name) {
  538. let canvas = this.canvas
  539. let image = canvas
  540. .toDataURL('image/png')
  541. .replace('image/png', 'image/octet-stream')
  542. let link = document.createElement('a')
  543. let blob = Util.dataURLtoBlob(image)
  544. let objUrl = URL.createObjectURL(blob)
  545. link.download = `${name || 'scene'}.png`
  546. link.href = objUrl
  547. link.click()
  548. return this
  549. }
  550. /**
  551. * Adds a plugin
  552. * @param plugin
  553. * @returns {Viewer}
  554. */
  555. use(plugin) {
  556. if (plugin && plugin.install) {
  557. plugin.install(this)
  558. }
  559. return this
  560. }
  561. }
  562. export default Viewer