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.

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