Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Viewer.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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. get level() {
  155. return this._delegate.scene.globe._surface._debug.maxDepthVisited
  156. }
  157. /***
  158. *
  159. * @param layerGroup
  160. * @private
  161. */
  162. _addLayerGroup(layerGroup) {
  163. if (
  164. layerGroup?.layerGroupEvent &&
  165. !Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  166. ) {
  167. layerGroup.layerGroupEvent.fire(LayerGroupEventType.ADD, this)
  168. this._layerGroupCache[layerGroup.id] = layerGroup
  169. }
  170. }
  171. /**
  172. *
  173. * @param layerGroup
  174. * @private
  175. */
  176. _removeLayerGroup(layerGroup) {
  177. if (
  178. layerGroup?.layerGroupEvent &&
  179. Object(this._layerGroupCache).hasOwnProperty(layerGroup.id)
  180. ) {
  181. layerGroup.layerGroupEvent.fire(LayerGroupEventType.REMOVE, this)
  182. delete this._layerGroupCache[layerGroup.id]
  183. }
  184. }
  185. /**
  186. * @param layer
  187. * @private
  188. */
  189. _addLayer(layer) {
  190. !this._layerCache[layer.type] && (this._layerCache[layer.type] = {})
  191. if (!Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)) {
  192. layer.fire(LayerEventType.ADD, this)
  193. this._layerCache[layer.type][layer.id] = layer
  194. }
  195. }
  196. /**
  197. * @param layer
  198. * @private
  199. */
  200. _removeLayer(layer) {
  201. if (Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)) {
  202. layer.fire(LayerEventType.REMOVE, this)
  203. delete this._layerCache[layer.type][layer.id]
  204. }
  205. }
  206. /**
  207. * Sets viewer options
  208. * @param options
  209. * @returns {Viewer}
  210. */
  211. setOptions(options) {
  212. this._viewerOption.setOptions(options)
  213. return this
  214. }
  215. /**
  216. * Sets camera pitch range
  217. * @param min
  218. * @param max
  219. * @returns {Viewer}
  220. */
  221. setPitchRange(min = -90, max = -20) {
  222. this._cameraOption.setPitchRange(min, max)
  223. return this
  224. }
  225. /**
  226. * @param west
  227. * @param south
  228. * @param east
  229. * @param north
  230. * @returns {Viewer}
  231. */
  232. setBounds(west, south, east, north) {
  233. this._cameraOption.setBounds(west, south, east, north)
  234. return this
  235. }
  236. /**
  237. * Changes Scene Mode,2:2D,2.5:2.5D,3:3D
  238. * @param sceneMode
  239. * @param duration
  240. * @returns {Viewer}
  241. */
  242. changeSceneMode(sceneMode, duration = 0) {
  243. if (sceneMode === 2) {
  244. this._delegate.scene.morphTo2D(duration)
  245. } else if (sceneMode === 3) {
  246. this._delegate.scene.morphTo3D(duration)
  247. } else if (sceneMode === 2.5) {
  248. this._delegate.scene.morphToColumbusView(duration)
  249. }
  250. return this
  251. }
  252. /**
  253. * Changes Mouse Mode,0:Default,1: Change the tiltEventTypes to CameraEventType.RIGHT_DRAG
  254. * @param mouseMode
  255. * @returns {Viewer}
  256. */
  257. changeMouseMode(mouseMode) {
  258. this._cameraOption.changeMouseMode(mouseMode)
  259. return this
  260. }
  261. /**
  262. * Adds the baseLayer .
  263. * The baseLayer can be a single or an array,
  264. * and when the baseLayer is an array, the baseLayer will be loaded together
  265. * @param baseLayers
  266. * @param options
  267. * @returns {Viewer}
  268. */
  269. addBaseLayer(baseLayers, options = {}) {
  270. if (!baseLayers) {
  271. return this
  272. }
  273. this._baseLayerPicker.imageryProviderViewModels.push(
  274. new Cesium.ProviderViewModel({
  275. name: options.name || '地图',
  276. tooltip: options.tooltip || '地图',
  277. iconUrl: '',
  278. creationFunction: () => {
  279. return baseLayers
  280. }
  281. })
  282. )
  283. if (!this._baseLayerPicker.selectedImagery) {
  284. this._baseLayerPicker.selectedImagery = this._baseLayerPicker.imageryProviderViewModels[0]
  285. }
  286. this.mapSwitch && this.mapSwitch.addMap(options)
  287. return this
  288. }
  289. /**
  290. * Changes the current globe display of the baseLayer
  291. * @param index
  292. * @returns {Viewer}
  293. */
  294. changeBaseLayer(index) {
  295. if (this._baseLayerPicker && index >= 0) {
  296. this._baseLayerPicker.selectedImagery = this._baseLayerPicker.imageryProviderViewModels[
  297. index
  298. ]
  299. }
  300. return this
  301. }
  302. /**
  303. *
  304. * @param windowPosition
  305. * @returns {Promise}
  306. */
  307. getImageryLayerInfo(windowPosition) {
  308. let ray = this._delegate.camera.getPickRay(windowPosition)
  309. return this._delegate.imageryLayers.pickImageryLayerFeatures(
  310. ray,
  311. this._delegate.scene
  312. )
  313. }
  314. /**
  315. * Adds the terrain
  316. * @param terrain
  317. * @param options
  318. * @returns {Viewer}
  319. */
  320. addTerrain(terrain, options = {}) {
  321. if (!terrain) {
  322. return this
  323. }
  324. this._baseLayerPicker.terrainProviderViewModels.push(
  325. new Cesium.ProviderViewModel({
  326. name: options.name || '地形',
  327. tooltip: options.tooltip || '地形',
  328. creationFunction: () => {
  329. return terrain
  330. }
  331. })
  332. )
  333. if (!this._baseLayerPicker.selectedTerrain) {
  334. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[0]
  335. }
  336. return this
  337. }
  338. /**
  339. * Changes the current globe display of the terrain
  340. * @param index
  341. * @returns {Viewer}
  342. */
  343. changeTerrain(index) {
  344. if (this._baseLayerPicker && index >= 0) {
  345. this._baseLayerPicker.selectedTerrain = this._baseLayerPicker.terrainProviderViewModels[
  346. index
  347. ]
  348. }
  349. return this
  350. }
  351. /**
  352. * Removes terrain
  353. * @returns {Viewer}
  354. */
  355. removeTerrain() {
  356. this._baseLayerPicker.terrainProviderViewModels = []
  357. this._baseLayerPicker.selectedTerrain = undefined
  358. this._delegate.terrainProvider = new Cesium.EllipsoidTerrainProvider()
  359. return this
  360. }
  361. /**
  362. *
  363. * @param layerGroup
  364. * @returns {Viewer}
  365. */
  366. addLayerGroup(layerGroup) {
  367. this._addLayerGroup(layerGroup)
  368. return this
  369. }
  370. /**
  371. *
  372. * @param layerGroup
  373. * @returns {Viewer}
  374. */
  375. removeLayerGroup(layerGroup) {
  376. this._removeLayerGroup(layerGroup)
  377. return this
  378. }
  379. /**
  380. *
  381. * @param id
  382. * @returns {undefined}
  383. */
  384. getLayerGroup(id) {
  385. return this._layerGroupCache[id] || undefined
  386. }
  387. /**
  388. * add a layer
  389. * @param layer
  390. * @returns {Viewer}
  391. */
  392. addLayer(layer) {
  393. this._addLayer(layer)
  394. return this
  395. }
  396. /**
  397. * Removes a layer
  398. * @param layer
  399. * @returns {Viewer}
  400. */
  401. removeLayer(layer) {
  402. this._removeLayer(layer)
  403. return this
  404. }
  405. /**
  406. * Checks to see if the layer is included
  407. * @param layer
  408. * @returns {boolean}
  409. */
  410. hasLayer(layer) {
  411. return Object(this._layerCache[layer.type]).hasOwnProperty(layer.id)
  412. }
  413. /**
  414. * Returns a layer by id
  415. * @param id
  416. * @returns {*|undefined}
  417. */
  418. getLayer(id) {
  419. let filters = this.getLayers().filter(item => item.id === id)
  420. return filters && filters.length ? filters[0] : undefined
  421. }
  422. /**
  423. * Returns all layers
  424. * @returns {[]}
  425. */
  426. getLayers() {
  427. let result = []
  428. Object.keys(this._layerCache).forEach(type => {
  429. let cache = this._layerCache[type]
  430. Object.keys(cache).forEach(layerId => {
  431. result.push(cache[layerId])
  432. })
  433. })
  434. return result
  435. }
  436. /**
  437. * Iterate through each layer and pass it as an argument to the callback function
  438. * @param method
  439. * @param context
  440. * @returns {Viewer}
  441. */
  442. eachLayer(method, context) {
  443. Object.keys(this._layerCache).forEach(type => {
  444. let cache = this._layerCache[type]
  445. Object.keys(cache).forEach(layerId => {
  446. method.call(context, cache[layerId])
  447. })
  448. })
  449. return this
  450. }
  451. /**
  452. * @param target
  453. * @param duration
  454. * @returns {Viewer}
  455. */
  456. flyTo(target, duration) {
  457. this._delegate.flyTo(target?.delegate || target, {
  458. duration
  459. })
  460. return this
  461. }
  462. /**
  463. * @param target
  464. * @returns {Viewer}
  465. */
  466. zoomTo(target) {
  467. this._delegate.zoomTo(target?.delegate || target)
  468. return this
  469. }
  470. /**
  471. * Camera fly to a position
  472. * @param position
  473. * @param completeCallback
  474. * @param duration
  475. * @returns {Viewer}
  476. */
  477. flyToPosition(position, completeCallback, duration) {
  478. position = Parse.parsePosition(position)
  479. this.camera.flyTo({
  480. destination: Transform.transformWGS84ToCartesian(position),
  481. orientation: {
  482. heading: Cesium.Math.toRadians(position.heading),
  483. pitch: Cesium.Math.toRadians(position.pitch),
  484. roll: Cesium.Math.toRadians(position.roll)
  485. },
  486. complete: completeCallback,
  487. duration: duration
  488. })
  489. return this
  490. }
  491. /**
  492. * Camera zoom to a position
  493. * @param position
  494. * @param completeCallback
  495. * @returns {Viewer}
  496. */
  497. zoomToPosition(position, completeCallback) {
  498. this.flyToPosition(position, completeCallback, 0)
  499. return this
  500. }
  501. /**
  502. * Camera fly to bounds
  503. * @param bounds
  504. * @param heading
  505. * @param pitch
  506. * @param roll
  507. * @param completeCallback
  508. * @param duration
  509. * @return {Viewer}
  510. */
  511. flyToBounds(
  512. bounds,
  513. { heading = 0, pitch = 0, roll = 0 },
  514. completeCallback,
  515. duration
  516. ) {
  517. if (!bounds) {
  518. return this
  519. }
  520. if (!Array.isArray(bounds)) {
  521. bounds = bounds.split(',')
  522. }
  523. this.camera.flyTo({
  524. destination: Cesium.Rectangle.fromDegrees(
  525. bounds[0],
  526. bounds[1],
  527. bounds[2],
  528. bounds[3]
  529. ),
  530. orientation: {
  531. heading: Cesium.Math.toRadians(heading),
  532. pitch: Cesium.Math.toRadians(pitch),
  533. roll: Cesium.Math.toRadians(roll)
  534. },
  535. complete: completeCallback,
  536. duration: duration
  537. })
  538. return this
  539. }
  540. /**
  541. *
  542. * @param bounds
  543. * @param heading
  544. * @param pitch
  545. * @param roll
  546. * @param completeCallback
  547. * @return {Viewer}
  548. */
  549. zoomToBounds(bounds, { heading = 0, pitch = 0, roll = 0 }, completeCallback) {
  550. this.flyToBounds(bounds, { heading, pitch, roll }, completeCallback)
  551. return this
  552. }
  553. /**
  554. *
  555. * @param type
  556. * @param callback
  557. * @param context
  558. * @returns {Viewer}
  559. */
  560. on(type, callback, context) {
  561. this._viewerEvent.on(type, callback, context || this)
  562. this._sceneEvent.on(type, callback, context || this)
  563. return this
  564. }
  565. /**
  566. *
  567. * @param type
  568. * @param callback
  569. * @param context
  570. * @returns {Viewer}
  571. */
  572. once(type, callback, context) {
  573. this._viewerEvent.once(type, callback, context || this)
  574. return this
  575. }
  576. /**
  577. *
  578. * @param type
  579. * @param callback
  580. * @param context
  581. * @returns {Viewer}
  582. */
  583. off(type, callback, context) {
  584. this._viewerEvent.off(type, callback, context || this)
  585. this._sceneEvent.off(type, callback, context || this)
  586. return this
  587. }
  588. /**
  589. * Destroys the viewer.
  590. */
  591. destroy() {
  592. Object.keys(this._layerCache).forEach(type => {
  593. let cache = this._layerCache[type]
  594. Object.keys(cache).forEach(layerId => {
  595. this._removeLayer(cache[layerId])
  596. })
  597. })
  598. this._delegate.destroy()
  599. this._delegate = undefined
  600. this._baseLayerPicker = undefined
  601. this._layerCache = {}
  602. this._dcContainer.parentNode.removeChild(this._dcContainer)
  603. this._dcContainer = undefined
  604. return this
  605. }
  606. /**
  607. * Export scene to image
  608. * @param name
  609. * @returns {Viewer}
  610. */
  611. exportScene(name) {
  612. let canvas = this.canvas
  613. let image = canvas
  614. .toDataURL('image/png')
  615. .replace('image/png', 'image/octet-stream')
  616. let link = document.createElement('a')
  617. let blob = Util.dataURLtoBlob(image)
  618. let objUrl = URL.createObjectURL(blob)
  619. link.download = `${name || 'scene'}.png`
  620. link.href = objUrl
  621. link.click()
  622. return this
  623. }
  624. /**
  625. * Adds a plugin
  626. * @param plugin
  627. * @returns {Viewer}
  628. */
  629. use(plugin) {
  630. if (plugin && plugin.install) {
  631. plugin.install(this)
  632. }
  633. return this
  634. }
  635. }
  636. export default Viewer