You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  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. import createTools from '@dc-modules/tools'
  19. const DEF_OPTS = {
  20. animation: false, //Whether to create animated widgets, lower left corner of the meter
  21. baseLayerPicker: false, //Whether to display the layer selector
  22. imageryProvider: false, // Whether to display the default imagery
  23. fullscreenButton: false, //Whether to display the full-screen button
  24. geocoder: false, //To display the geocoder widget, query the button in the upper right corner
  25. homeButton: false, //Whether to display the Home button
  26. infoBox: false, //Whether to display the information box
  27. sceneModePicker: false, //Whether to display 3D/2D selector
  28. selectionIndicator: false, //Whether to display the selection indicator component
  29. timeline: false, //Whether to display the timeline
  30. navigationHelpButton: false, //Whether to display the help button in the upper right corner
  31. navigationInstructionsInitiallyVisible: false,
  32. creditContainer: undefined,
  33. shouldAnimate: true
  34. }
  35. class Viewer {
  36. constructor(id, options = {}) {
  37. if (!id || (typeof id === 'string' && !document.getElementById(id))) {
  38. throw new Error('Viewer:the id is empty')
  39. }
  40. this._delegate = new Cesium.Viewer(id, {
  41. ...DEF_OPTS,
  42. ...options
  43. }) // Initialize the viewer
  44. /**
  45. * Registers events
  46. */
  47. new MouseEvent(this) // Register global mouse events
  48. this._viewerEvent = new ViewerEvent() // Register viewer events
  49. this._sceneEvent = new SceneEvent(this) // Register scene events
  50. this._viewerOption = new ViewerOption(this) // Initialize the viewer option
  51. this._cameraOption = new CameraOption(this) // Initialize the camera option
  52. this._dcContainer = DomUtil.create(
  53. 'div',
  54. 'dc-container',
  55. typeof id === 'string' ? document.getElementById(id) : id
  56. ) //Register the custom container
  57. this._baseLayerPicker = new Cesium.BaseLayerPickerViewModel({
  58. globe: this._delegate.scene.globe
  59. }) //Initialize the baseLayer picker
  60. this._layerGroupCache = {}
  61. this._layerCache = {}
  62. /**
  63. * Registers default widgets
  64. */
  65. let widgets = createWidgets()
  66. Object.keys(widgets).forEach(key => {
  67. this.use(widgets[key])
  68. })
  69. /**
  70. * Registers default tools
  71. */
  72. let tools = createTools()
  73. Object.keys(tools).forEach(key => {
  74. this.use(tools[key])
  75. })
  76. }
  77. get delegate() {
  78. return this._delegate
  79. }
  80. get dcContainer() {
  81. return this._dcContainer
  82. }
  83. get scene() {
  84. return this._delegate.scene
  85. }
  86. get camera() {
  87. return this._delegate.camera
  88. }
  89. get canvas() {
  90. return this._delegate.scene.canvas
  91. }
  92. get dataSources() {
  93. return this._delegate.dataSources
  94. }
  95. get imageryLayers() {
  96. return this._delegate.imageryLayers
  97. }
  98. get terrainProvider() {
  99. return this._delegate.terrainProvider
  100. }
  101. get entities() {
  102. return this._delegate.entities
  103. }
  104. get postProcessStages() {
  105. return this._delegate.scene.postProcessStages
  106. }
  107. get clock() {
  108. return this._delegate.clock
  109. }
  110. get viewerEvent() {
  111. return this._viewerEvent
  112. }
  113. get cameraPosition() {
  114. let position = Transform.transformCartesianToWGS84(this.camera.positionWC)
  115. if (position) {
  116. position.heading = Cesium.Math.toDegrees(this.camera.heading)
  117. position.pitch = Cesium.Math.toDegrees(this.camera.pitch)
  118. position.roll = Cesium.Math.toDegrees(this.camera.roll)
  119. }
  120. return position
  121. }
  122. get resolution() {
  123. let width = this.scene.canvas.width
  124. let height = this.scene.canvas.height
  125. let min = Transform.transformWindowToWGS84(
  126. new Cesium.Cartesian2((width / 2) | 0, height - 1),
  127. this
  128. )
  129. let max = Transform.transformWindowToWGS84(
  130. new Cesium.Cartesian2((1 + width / 2) | 0, height - 1),
  131. this
  132. )
  133. if (!min || !max) {
  134. return 1
  135. }
  136. return Math.abs(min.lng - max.lng)
  137. }
  138. get viewBounds() {
  139. let width = this.scene.canvas.width
  140. let height = this.scene.canvas.height
  141. let min = Transform.transformWindowToWGS84(
  142. new Cesium.Cartesian2(0, height),
  143. this
  144. )
  145. let max = Transform.transformWindowToWGS84(
  146. new Cesium.Cartesian2(width, 0),
  147. this
  148. )
  149. if (!min || !max) {
  150. return Cesium.Rectangle.MAX_VALUE
  151. }
  152. return Cesium.Rectangle.fromDegrees(min.lng, min.lat, max.lng, max.lat)
  153. }
  154. /***
  155. *
  156. * @param layerGroup
  157. * @private
  158. */
  159. _addLayerGroup(layerGroup) {
  160. if (
  161. layerGroup?.layerGroupEvent &&
  162. !Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  163. ) {
  164. layerGroup.layerGroupEvent.fire(LayerGroupEventType.ADD, this)
  165. this._layerGroupCache[layerGroup.id] = layerGroup
  166. }
  167. }
  168. /**
  169. *
  170. * @param layerGroup
  171. * @private
  172. */
  173. _removeLayerGroup(layerGroup) {
  174. if (
  175. layerGroup?.layerGroupEvent &&
  176. Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  177. ) {
  178. layerGroup.layerGroupEvent.fire(LayerGroupEventType.REMOVE, this)
  179. delete this._layerGroupCache[layerGroup.id]
  180. }
  181. }
  182. /**
  183. * @param layer
  184. * @private
  185. */
  186. _addLayer(layer) {
  187. !this._layerCache[layer.type] && (this._layerCache[layer.type] = {})
  188. if (!Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)) {
  189. layer.fire(LayerEventType.ADD, this)
  190. this._layerCache[layer.type][layer.id] = layer
  191. }
  192. }
  193. /**
  194. * @param layer
  195. * @private
  196. */
  197. _removeLayer(layer) {
  198. if (Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)) {
  199. layer.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. *
  299. * @param windowPosition
  300. * @returns {Promise}
  301. */
  302. getImageryLayerInfo(windowPosition) {
  303. let ray = this._delegate.camera.getPickRay(windowPosition)
  304. return this._delegate.imageryLayers.pickImageryLayerFeatures(
  305. ray,
  306. this._delegate.scene
  307. )
  308. }
  309. /**
  310. * Adds the terrain
  311. * @param terrain
  312. * @param options
  313. * @returns {Viewer}
  314. */
  315. addTerrain(terrain, options = {}) {
  316. if (!terrain) {
  317. return this
  318. }
  319. this._baseLayerPicker.terrainProviderViewModels.push(
  320. new Cesium.ProviderViewModel({
  321. name: options.name || '地形',
  322. creationFunction: () => {
  323. return terrain
  324. }
  325. })
  326. )
  327. if (!this._baseLayerPicker.selectedTerrain) {
  328. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[0]
  329. }
  330. return this
  331. }
  332. /**
  333. * Changes the current globe display of the terrain
  334. * @param index
  335. * @returns {Viewer}
  336. */
  337. changeTerrain(index) {
  338. if (this._baseLayerPicker && index >= 0) {
  339. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[
  340. index
  341. ]
  342. }
  343. return this
  344. }
  345. /**
  346. * Removes terrain
  347. * @returns {Viewer}
  348. */
  349. removeTerrain() {
  350. this._baseLayerPicker.terrainProviderViewModels = []
  351. this._baseLayerPicker.selectedTerrain = undefined
  352. this._delegate.terrainProvider = new Cesium.EllipsoidTerrainProvider()
  353. return this
  354. }
  355. /**
  356. *
  357. * @param layerGroup
  358. * @returns {Viewer}
  359. */
  360. addLayerGroup(layerGroup) {
  361. this._addLayerGroup(layerGroup)
  362. return this
  363. }
  364. /**
  365. *
  366. * @param layerGroup
  367. * @returns {Viewer}
  368. */
  369. removeLayerGroup(layerGroup) {
  370. this._removeLayerGroup(layerGroup)
  371. return this
  372. }
  373. /**
  374. *
  375. * @param id
  376. * @returns {undefined}
  377. */
  378. getLayerGroup(id) {
  379. return this._layerGroupCache[id] || undefined
  380. }
  381. /**
  382. * add a layer
  383. * @param layer
  384. * @returns {Viewer}
  385. */
  386. addLayer(layer) {
  387. this._addLayer(layer)
  388. return this
  389. }
  390. /**
  391. * Removes a layer
  392. * @param layer
  393. * @returns {Viewer}
  394. */
  395. removeLayer(layer) {
  396. this._removeLayer(layer)
  397. return this
  398. }
  399. /**
  400. * Checks to see if the layer is included
  401. * @param layer
  402. * @returns {boolean}
  403. */
  404. hasLayer(layer) {
  405. return Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)
  406. }
  407. /**
  408. * Returns a layer by id
  409. * @param id
  410. * @returns {*|undefined}
  411. */
  412. getLayer(id) {
  413. let filters = this.getLayers().filter(item => item.id === id)
  414. return filters && filters.length ? filters[0] : undefined
  415. }
  416. /**
  417. * Returns all layers
  418. * @returns {[]}
  419. */
  420. getLayers() {
  421. let result = []
  422. Object.keys(this._layerCache).forEach(type => {
  423. let cache = this._layerCache[type]
  424. Object.keys(cache).forEach(layerId => {
  425. result.push(cache[layerId])
  426. })
  427. })
  428. return result
  429. }
  430. /**
  431. * Iterate through each layer and pass it as an argument to the callback function
  432. * @param method
  433. * @param context
  434. * @returns {Viewer}
  435. */
  436. eachLayer(method, context) {
  437. Object.keys(this._layerCache).forEach(type => {
  438. let cache = this._layerCache[type]
  439. Object.keys(cache).forEach(layerId => {
  440. method.call(context, cache[layerId])
  441. })
  442. })
  443. return this
  444. }
  445. /**
  446. * @param target
  447. * @param duration
  448. * @returns {Viewer}
  449. */
  450. flyTo(target, duration) {
  451. this._delegate.flyTo(target?.delegate || target, {
  452. duration
  453. })
  454. return this
  455. }
  456. /**
  457. * @param target
  458. * @returns {Viewer}
  459. */
  460. zoomTo(target) {
  461. this._delegate.zoomTo(target?.delegate || target)
  462. return this
  463. }
  464. /**
  465. * Camera fly to a position
  466. * @param position
  467. * @param completeCallback
  468. * @param duration
  469. * @returns {Viewer}
  470. */
  471. flyToPosition(position, completeCallback, duration) {
  472. position = Parse.parsePosition(position)
  473. this.camera.flyTo({
  474. destination: Transform.transformWGS84ToCartesian(position),
  475. orientation: {
  476. heading: Cesium.Math.toRadians(position.heading),
  477. pitch: Cesium.Math.toRadians(position.pitch),
  478. roll: Cesium.Math.toRadians(position.roll)
  479. },
  480. complete: completeCallback,
  481. duration: duration
  482. })
  483. return this
  484. }
  485. /**
  486. * Camera zoom to a position
  487. * @param position
  488. * @param completeCallback
  489. * @returns {Viewer}
  490. */
  491. zoomToPosition(position, completeCallback) {
  492. this.flyToPosition(position, completeCallback, 0)
  493. return this
  494. }
  495. /**
  496. *
  497. * @param type
  498. * @param callback
  499. * @param context
  500. * @returns {Viewer}
  501. */
  502. on(type, callback, context) {
  503. this._viewerEvent.on(type, callback, context || this)
  504. this._sceneEvent.on(type, callback, context || this)
  505. return this
  506. }
  507. /**
  508. *
  509. * @param type
  510. * @param callback
  511. * @param context
  512. * @returns {Viewer}
  513. */
  514. once(type, callback, context) {
  515. this._viewerEvent.once(type, callback, context || this)
  516. return this
  517. }
  518. /**
  519. *
  520. * @param type
  521. * @param callback
  522. * @param context
  523. * @returns {Viewer}
  524. */
  525. off(type, callback, context) {
  526. this._viewerEvent.off(type, callback, context || this)
  527. this._sceneEvent.off(type, callback, context || this)
  528. return this
  529. }
  530. /**
  531. * Destroys the viewer.
  532. */
  533. destroy() {
  534. Object.keys(this._layerCache).forEach(type => {
  535. let cache = this._layerCache[type]
  536. Object.keys(cache).forEach(layerId => {
  537. this._removeLayer(cache[layerId])
  538. })
  539. })
  540. this._delegate.destroy()
  541. this._delegate = undefined
  542. this._baseLayerPicker = undefined
  543. this._layerCache = {}
  544. this._dcContainer.parentNode.removeChild(this._dcContainer)
  545. this._dcContainer = undefined
  546. return this
  547. }
  548. /**
  549. * Export scene to image
  550. * @param name
  551. * @returns {Viewer}
  552. */
  553. exportScene(name) {
  554. let canvas = this.canvas
  555. let image = canvas
  556. .toDataURL('image/png')
  557. .replace('image/png', 'image/octet-stream')
  558. let link = document.createElement('a')
  559. let blob = Util.dataURLtoBlob(image)
  560. let objUrl = URL.createObjectURL(blob)
  561. link.download = `${name || 'scene'}.png`
  562. link.href = objUrl
  563. link.click()
  564. return this
  565. }
  566. /**
  567. * Adds a plugin
  568. * @param plugin
  569. * @returns {Viewer}
  570. */
  571. use(plugin) {
  572. if (plugin && plugin.install) {
  573. plugin.install(this)
  574. }
  575. return this
  576. }
  577. }
  578. export default Viewer