JTMap3D.js 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496
  1. /**
  2. * 创建者:王成
  3. * 创建日期:2021年11月8日
  4. * 描述:Cesium三维图层
  5. */
  6. /**
  7. * 标注层标识
  8. */
  9. var labelFlag = "_label";
  10. /**
  11. * 绘制模式 包括点 线 面 矩形 点 空
  12. */
  13. var ActionType = {
  14. measureLength: 'measureLength', //测量长度动作
  15. measureArea: 'measureArea', //测量面积动作
  16. queryAttribute: 'queryAttribute', //查询属性动作
  17. clipBIM: 'clipBIM', //切割BIM模型动作
  18. flightAround: 'flightAround', //环绕飞行
  19. non: 'non', //null动作
  20. casePointQuery: 'casePointQuery', //案件点查询
  21. casePolygonQuery: 'casePolygonQuery', //案件区域查询
  22. }
  23. /**
  24. * 构造函数
  25. * @param {JSON} options 选项
  26. */
  27. function CrMap(options) {
  28. this._init(options);
  29. }
  30. /**
  31. * 原型设置 必须的
  32. * @param {JSON} options 选项
  33. */
  34. CrMap.prototype.extend = function(options) {
  35. for (var key in options) {
  36. CrMap.prototype[key] = options[key];
  37. }
  38. }
  39. /**
  40. * 私有函数集合
  41. */
  42. CrMap.prototype.extend({
  43. /**
  44. * 初始化函数
  45. * @param {JSON} options 选项
  46. */
  47. _init: function(options) {
  48. if (options.selector == undefined) {
  49. console.error('未设置地图容器!')
  50. return;
  51. }
  52. //局部变量
  53. this.selector = options.selector; //3D地图容器
  54. this.serverUrl = options.serverUrl;
  55. this.viewer = undefined; //地图
  56. //事件
  57. this.onMouseMove = options.onMouseMove; //鼠标移动事件
  58. this.onShowTooltip = options.onShowTooltip; //显示移动弹窗回调
  59. this.onQueryVectorResult = options.onQueryVectorResult; //矢量数据查询回调
  60. this.onQueryStart = options.onQueryStart; //查询开始回调
  61. this.onExtentChange = options.onExtentChange; //地图范围变化事件
  62. this.onPostSceneChange = options.onPostSceneChange; //场景变化后事件
  63. this.onPopoverQueryTool = options.onPopoverQueryTool; //查询工具 此处指案件
  64. /* 属性查询相关 */
  65. this.queryLayers = []; //查询图层数组
  66. this.attributesQueryIndex = 0; //服务图层查询索引
  67. this.attributesData = []; //属性查询的数据
  68. this.rightInfoIndex = undefined;
  69. this.attributesEntity = []; //Entity查询的内容 需要与attributesData中保持一致
  70. //全局变量
  71. this.beforeLayerIds = []; //预知的图层Id集合 如果是后添加图层 则必须告知该参数
  72. this.imageryLayers = undefined; //图层数组
  73. this.primitives = undefined; //原语集合
  74. this.entities = undefined; //实体集合
  75. this.dataSources = undefined; //数据源数组
  76. //切割相关
  77. this.planeTargetY = 30; //ClippingPlane距离原点的距离
  78. this.planeSelected = undefined; // 鼠标选中的ClippingPlane
  79. //测量相关变量
  80. this.actionType = ActionType.non; //鼠标动作
  81. this.measurePoints = []; //测量数组
  82. this.measureTempPoints = []; //测量面积数组
  83. this.measurePolyline = undefined; //测量线
  84. this.measurePolygon = undefined; //测量面
  85. this.measureDistanceResult = 0; //测量长度
  86. this.measureAreaResult = 0; //测量面积
  87. //测量绘制点样式
  88. this.measurePointStyle = {
  89. pixelSize: 8,
  90. color: this._toColor(0, 154, 94, 1.0),
  91. outlineColor: this._toColor(255, 255, 255, 1.0),
  92. outlineWidth: 1.0
  93. };
  94. //测量结果标注样式
  95. this.measureLabelStyle = {
  96. font: '12px sans-serif',
  97. fillColor: this._toColor(255, 255, 255, 1.0),
  98. outlineColor: this._toColor(0, 154, 94, 1.0),
  99. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  100. outlineWidth: 1.0,
  101. verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
  102. pixelOffset: new Cesium.Cartesian2(0, -28),
  103. showBackground: true,
  104. backgroundColor: this._toColor(0, 0, 0, 0.6),
  105. };
  106. //环绕飞行相关
  107. this.angle = 0.1; //每次旋转的角度 值越大 旋转越快
  108. this.flightListner = undefined; //环绕飞行监听函数
  109. //区域旋转相关
  110. this.areaRotation = Cesium.Math.toRadians(30);
  111. //案件标注图层文字及广告牌相关
  112. this.caseLabels = undefined;
  113. this.caseLabelBillboards = undefined;
  114. //初始化地图
  115. this._init3DMap();
  116. //注册事件
  117. this._eventRegister();
  118. },
  119. /**
  120. * 初始化三维地图
  121. */
  122. _init3DMap: function() {
  123. this.viewer = new Cesium.Viewer(this.selector, {
  124. animation: false, //是否显示动画控件
  125. baseLayerPicker: false, //地图切换控件(底图以及地形图)是否显示,默认显示true
  126. timeline: false, //是否显示时间线控件,默认true
  127. navigationHelpButton: false, //是否显示帮助信息控件
  128. sceneModePicker: false, //是否显示3D/2D选择器
  129. infoBox: false, //点击要素之后显示的信息,默认true
  130. clampToGround: true, //开启贴地
  131. homeButton: false, //主页按钮,默认true
  132. geocoder: false, //地名查找,默认true
  133. scene3DOnly: true, //如果设置为true,则所有几何图形以3D模式绘制以节约GPU资源
  134. fullscreenButton: false, //全屏按钮,默认显示true
  135. shadows: false, //阴影
  136. // terrainExaggeration: 3.0, //地形夸大
  137. // imageryProvider: new Cesium.TileMapServiceImageryProvider({
  138. // url: 'https://a.tile.openstreetmap.org/'
  139. // }),
  140. imageryProvider: new Cesium.SingleTileImageryProvider({
  141. url: Cesium.buildModuleUrl('Assets/Images/earth_3.jpg'),
  142. }),
  143. selectionIndicator: false, //选中元素显示,默认true选中元素显示,默认true
  144. });
  145. this.viewer._cesiumWidget._creditContainer.style.display = "none"; //隐藏版本信息
  146. /* 此项设置为true可以查看哪些内容掉到地下了 正常情况下设置为false 否则会导致绘制的点只能看见一半 */
  147. this.viewer.scene.globe.depthTestAgainstTerrain = false; //地形不透明 地形检测
  148. // this.viewer.imageryLayers.get(0).show = false; //删除默认加载的影像,显示蓝色地球
  149. this.viewer.scene.skyBox.show = false; //是否显示星空
  150. this.viewer.scene.sun.show = true; //是否显示太阳
  151. this.viewer.scene.moon.show = false; //是否显示有月亮
  152. this.viewer.scene.skyAtmosphere.show = true; //是否隐藏大气圈
  153. this.viewer.scene.globe.show = true; //是否显示地球
  154. this.viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType
  155. .LEFT_DOUBLE_CLICK); //取消鼠标左键双击
  156. this.viewer.scene.debugShowFramesPerSecond = false; //是否显示帧FPS
  157. this.viewer.scene.requestRenderMode = true; //启动主动渲染 这样地图加载完成后停止渲染 可节省CPU的开支
  158. //是否开启抗锯齿
  159. this.viewer.scene.fxaa = true;
  160. this.viewer.scene.postProcessStages.fxaa.enabled = true;
  161. this.imageryLayers = this.viewer.imageryLayers; //赋值图层管理
  162. this.primitives = this.viewer.scene.primitives; //原语集合
  163. this.entities = this.viewer.entities; //实体集合
  164. this.dataSources = this.viewer.dataSources; //数据源集合
  165. /* 案件标注 */
  166. this.caseLabels = this.viewer.scene.primitives.add(new Cesium.LabelCollection());
  167. this.caseLabelBillboards = this.viewer.scene.primitives.add(new Cesium.BillboardCollection());
  168. /* 开启精细渲染 不要太大 否则会导致效率下降 */
  169. this.viewer._cesiumWidget._supportsImageRenderingPixelated = Cesium.FeatureDetection
  170. .supportsImageRenderingPixelated();
  171. this.viewer._cesiumWidget._forceResize = true;
  172. if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
  173. var vtxf_dpr = window.devicePixelRatio;
  174. // 适度降低分辨率
  175. while (vtxf_dpr >= 2.0) {
  176. vtxf_dpr /= 2.0;
  177. }
  178. // alert(vtxf_dpr);
  179. this.viewer.resolutionScale = 2.6;
  180. }
  181. },
  182. /**
  183. * 注册事件
  184. */
  185. _eventRegister: function() {
  186. var self = this;
  187. //定义挂接画布的handler
  188. var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
  189. /* 挂接鼠标移动动作 */
  190. handler.setInputAction(function(moveEvent) {
  191. var pickMent = self.viewer.scene.pick(moveEvent.endPosition);
  192. var ray = self.viewer.camera.getPickRay(moveEvent.endPosition);
  193. var cartesian = self.viewer.scene.globe.pick(ray, self.viewer.scene);
  194. if (cartesian != undefined) {
  195. //世界坐标转地理坐标(弧度)
  196. var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian);
  197. //弧度转换为度
  198. var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math
  199. .PI * 180
  200. ];
  201. //如果挂接了鼠标移动事件 则输出
  202. if (self.onMouseMove != undefined) {
  203. self.onMouseMove(self._getCameraParameter());
  204. }
  205. }
  206. /* Tooltip标签回调 */
  207. if (Cesium.defined(pickMent)) {
  208. //鼠标移动到对象上 指的是Entity对象 如果注册了显示Toolstip的事件 则回调显示
  209. //传递内容包括html ptx pty offsetx offsety isVisible
  210. if (self.onShowTooltip != undefined && pickMent.id && pickMent.id.tooltip) {
  211. self.onShowTooltip({
  212. html: pickMent.id.tooltip.html,
  213. x: moveEvent.endPosition.x,
  214. y: moveEvent.endPosition.y,
  215. offsetx: pickMent.id.tooltip.anchor[0],
  216. offsety: pickMent.id.tooltip.anchor[1],
  217. visible: true,
  218. name: pickMent.id.name,
  219. height: self.viewer.camera.positionCartographic.height,
  220. });
  221. } else {
  222. if (self.onShowTooltip != undefined) {
  223. self.onShowTooltip({
  224. visible: false,
  225. name: undefined,
  226. });
  227. }
  228. }
  229. } else {
  230. if (self.onShowTooltip != undefined) {
  231. self.onShowTooltip({
  232. visible: false,
  233. name: undefined,
  234. });
  235. }
  236. }
  237. /* BIM模型剪裁 */
  238. if (Cesium.defined(self.planeSelected)) {
  239. // 计算鼠标移动的过程中产生的垂直高度距离
  240. var deltaY = moveEvent.startPosition.y - moveEvent.endPosition.y;
  241. self.planeTargetY += deltaY;
  242. }
  243. // /* 测量长度 */
  244. // if (self.actionType == ActionType.measureLength) {
  245. // self._eventMeasureLengthMouseMove(moveEvent)
  246. // }
  247. // /* 测量面积 */
  248. // if (self.actionType == ActionType.measureArea) {
  249. // self._eventMeasureLengthMouseMove(moveEvent)
  250. // }
  251. }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  252. /* 挂接鼠标点击动作 */
  253. handler.setInputAction(function(event) {
  254. var pick = self.viewer.scene.pick(event.position);
  255. //查询动作
  256. if (self.actionType == ActionType.queryAttribute) {
  257. if (self.onQueryStart != undefined) {
  258. self.onQueryStart();
  259. }
  260. self.attributesEntity = [];
  261. //Entity查询
  262. if (Cesium.defined(pick)) {
  263. //经过研究 统一一个出口
  264. if (pick.id != undefined) {
  265. if (pick.id.description != undefined) {
  266. var config = JSON.parse(pick.id.name);
  267. self.attributesEntity.push({
  268. layerName: config.name,
  269. attributes: JSON.parse(pick.id.description),
  270. geometry: config.geometry,
  271. });
  272. }
  273. }
  274. }
  275. //ArcGIS矢量图层查询
  276. self._queryVectorLayer(event.position);
  277. } else if (self.actionType == ActionType.measureLength) {
  278. self._eventMeasureLengthMouseClick(event);
  279. } else if (self.actionType == ActionType.measureArea) {
  280. self._eventMeasureAreaMouseClick(event);
  281. } else if (self.actionType == ActionType.flightAround) {
  282. if (self.flightListner != undefined) {
  283. self.viewer.clock.onTick.removeEventListener(self.flightListner);
  284. self.flightListner = undefined;
  285. self.actionType = ActionType.non;
  286. } else {
  287. self._startFlightAround(event);
  288. }
  289. } else if (self.actionType == ActionType.casePointQuery) {
  290. self._eventCasePointQueryMouseClick(event);
  291. } else if (self.actionType == ActionType.casePolygonQuery) {
  292. self._eventCasePolygonQueryMouseClick(event);
  293. }
  294. }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  295. /* 双指触摸变化事件 */
  296. handler.setInputAction(function(moveEvent) {
  297. //如果挂接了鼠标移动事件 则输出
  298. if (self.onMouseMove != undefined) {
  299. self.onMouseMove(self._getCameraParameter());
  300. }
  301. }, Cesium.ScreenSpaceEventType.PINCH_MOVE);
  302. /* 右键点击事件 */
  303. handler.setInputAction(function(event) {
  304. self._eventMeasureEnd(event);
  305. }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  306. /* 鼠标按下事件 */
  307. handler.setInputAction(function(event) {
  308. var pick = self.viewer.scene.pick(event.position);
  309. if (Cesium.defined(pick) && Cesium.defined(pick.id) && Cesium.defined(pick.id.plane)) {
  310. self.planeSelected = pick.id.plane;
  311. self.planeSelected.material = Cesium.Color.BLUE.withAlpha(0.3); // 更改选中的切面颜色
  312. self.planeSelected.outlineColor = Cesium.Color.WHITE;
  313. self.viewer.scene.screenSpaceCameraController.enableInputs = false; // 取消默认的鼠标一切输入事件
  314. }
  315. }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
  316. /* 鼠标松开事件 */
  317. handler.setInputAction(function(event) {
  318. if (Cesium.defined(self.planeSelected)) {
  319. self.planeSelected.material = Cesium.Color.RED.withAlpha(0.1); // 恢复选中的切面颜色
  320. self.planeSelected.outlineColor = Cesium.Color.WHITE;
  321. self.planeSelected = undefined;
  322. }
  323. self.viewer.scene.screenSpaceCameraController.enableInputs = true; // 恢复默认的鼠标一切输入事件
  324. }, Cesium.ScreenSpaceEventType.LEFT_UP);
  325. /* 相机移动结束事件 */
  326. self.viewer.camera.moveEnd.addEventListener(function(event) {
  327. //地图变化范围事件
  328. if (self.onExtentChange != undefined) {
  329. //获取当前地图范围
  330. var rect = self.viewer.camera.computeViewRectangle();
  331. var result = {
  332. west: self._arcToDegree(rect.west), //西
  333. south: self._arcToDegree(rect.south),
  334. east: self._arcToDegree(rect.east), //东
  335. north: self._arcToDegree(rect.north),
  336. pitch: self._arcToDegree(self.viewer.camera.pitch),
  337. heading: self._arcToDegree(self.viewer.camera.heading),
  338. height: self.viewer.camera.positionCartographic.height,
  339. }
  340. self.onExtentChange(result);
  341. };
  342. //如果挂接了鼠标移动事件 则输出
  343. if (self.onMouseMove != undefined) {
  344. self.onMouseMove(self._getCameraParameter());
  345. }
  346. });
  347. //渲染新帧后的更新/渲染周期结束时,
  348. self.viewer.scene.postRender.addEventListener(function() {
  349. if (self.onPostSceneChange != undefined) {
  350. self.resetLabelLocation();
  351. /* 需要传递一些参数出去 */
  352. self.onPostSceneChange({
  353. pitch: self._arcToDegree(self.viewer.camera.pitch),
  354. heading: self._arcToDegree(self.viewer.camera.heading),
  355. height: self.viewer.camera.positionCartographic.height,
  356. });
  357. }
  358. });
  359. },
  360. /**
  361. * 查询ArcGIS服务图层的地图范围
  362. * @param {string} url 服务地址
  363. * @param {int} index 图层索引
  364. * @param {JSON} callSuccess 成功回调{xmin:ymin:xmax:ymax:}
  365. * @param {string} callError 失败回调(errorString)
  366. */
  367. _queryAGServerExtent: function(url, index, callSuccess, callError) {
  368. $.ajax({
  369. async: true,
  370. type: 'POST',
  371. dataType: 'json',
  372. url: url + '/' + index + '?f=pjson',
  373. success: function(data) {
  374. if (callSuccess != undefined) {
  375. callSuccess({
  376. xmin: data.extent.xmin,
  377. ymin: data.extent.ymin,
  378. xmax: data.extent.xmax,
  379. ymax: data.extent.ymax,
  380. });
  381. }
  382. },
  383. error: function(XMLHttpRequest, textStatus, errorThrown) {
  384. //通常情况下textStatus和errorThrown只有其中一个包含信息
  385. if (callError != undefined) {
  386. callError(textStatus);
  387. }
  388. }
  389. });
  390. },
  391. /**
  392. * 查询ArcGIS服务图层的数据
  393. * @param {JSON} options
  394. * where{string}:查询条件
  395. * geometry{JSONString}:查询关联的要素 JSON字符串
  396. * fields{string}:需要查询的字段 逗号分隔开的字符串
  397. * returnGeometry{boolean}[true/false]:是否返回要素
  398. * @param {JSON} callSuccess 成功回调 返回的JSON数组
  399. * @param {String} callError 失败回调(errorString)
  400. */
  401. _queryArcGISGeoJSON: function(options, callSuccess, callError) {
  402. var queryParam = {}
  403. //查询文字条件
  404. if (options.where == undefined) {
  405. queryParam.where = "1=1";
  406. } else {
  407. queryParam.where = "1=1 and " + options.where;
  408. }
  409. queryParam.text = "";
  410. queryParam.objectIds = "";
  411. queryParam.time = "";
  412. //查询区域
  413. if (options.geometry == undefined) {
  414. queryParam.geometry = "";
  415. } else {
  416. queryParam.geometry = options.geometry;
  417. }
  418. /* 设置输入的查询区域类型 */
  419. queryParam.geometryType = options.geometryType == undefined ? "esriGeometryEnvelope" : options
  420. .geometryType;
  421. queryParam.inSR = "";
  422. queryParam.spatialRel = "esriSpatialRelIntersects";
  423. queryParam.relationParam = "";
  424. //查询字段集合
  425. if (options.fields == undefined) {
  426. queryParam.outFields = "*";
  427. } else {
  428. queryParam.outFields = options.fields;
  429. }
  430. if (options.returnGeometry == undefined) {
  431. queryParam.returnGeometry = false;
  432. } else {
  433. queryParam.returnGeometry = options.returnGeometry;
  434. }
  435. queryParam
  436. .maxAllowableOffset = "";
  437. queryParam.geometryPrecision = "";
  438. queryParam.outSR = "";
  439. queryParam.returnIdsOnly = false;
  440. queryParam.returnCountOnly = false;
  441. queryParam.orderByFields = "";
  442. queryParam.groupByFieldsForStatistics = "";
  443. queryParam.outStatistics = "";
  444. queryParam.returnZ = "";
  445. queryParam.returnM = "";
  446. queryParam.gdbVersion = "";
  447. queryParam.returnDistinctValues = "";
  448. queryParam.f = "pjson";
  449. /* 打印一下参数看看 */
  450. // console.log("服务要素查询参数 = " + JSON.stringify(queryParam));
  451. //开始查询
  452. $.ajax({
  453. async: true,
  454. type: 'POST',
  455. dataType: 'jsonp',
  456. contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
  457. url: options.url + '/query',
  458. data: queryParam,
  459. success: function(data) {
  460. if (data.error != undefined) {
  461. if (callError != undefined) callError(data.error.message);
  462. }
  463. if (callSuccess != undefined) callSuccess(data);
  464. },
  465. error: function(XMLHttpRequest, textStatus, errorThrown) {
  466. if (callError != undefined) callError(errorThrown);
  467. }
  468. });
  469. },
  470. /**
  471. * 检测当前的索引是否查过图层总数
  472. * @param {int} index 索引
  473. */
  474. _checkLayerIndex: function(index) {
  475. if (this.imageryLayers == undefined || index == undefined) return false;
  476. var layerIndex = parseFloat(index);
  477. if (layerIndex < this.imageryLayers.length) return true;
  478. else return false;
  479. },
  480. /**
  481. * @param {int} layerIndex 当前图层索引
  482. * @param {string} layerIndex
  483. */
  484. _consoleLayerInfo: function(layerIndex, layerId) {
  485. return;
  486. console.log("已有图层数量:" + this.imageryLayers.length + " 当前图层索引:" + layerIndex);
  487. var result = this._searchCorrelationLayerIndex(layerId);
  488. if (result == undefined) {
  489. console.log("图层Id=" + layerId + " 上下均未有关联图层!");
  490. } else {
  491. console.log("图层Id=" + layerId + " 底部图层索引=" + result.minIndex + " 顶部图层索引=" + result.maxIndex);
  492. }
  493. },
  494. /**
  495. * 搜索指定Id的上下关联图层索引
  496. * @param {string} layerId 图层Id
  497. */
  498. _searchCorrelationLayerIndex: function(layerId) {
  499. var index = this.beforeLayerIds.indexOf(layerId);
  500. if (index == -1) return undefined;
  501. var minIndex = -1;
  502. var maxIndex = -1;
  503. /* 找该图层底部的图层 */
  504. for (var i = index - 1; i >= 0; i--) {
  505. minIndex = this.imageryLayers.indexOf(window[this.beforeLayerIds[i]]);
  506. if (minIndex != -1) {
  507. break;
  508. }
  509. }
  510. /* 找该图层顶部的图层 */
  511. for (var i = index + 1; i < this.beforeLayerIds.length; i++) {
  512. maxIndex = this.imageryLayers.indexOf(window[this.beforeLayerIds[i]]);
  513. if (maxIndex != -1) {
  514. break;
  515. }
  516. }
  517. /* 返回寻找结果 */
  518. return {
  519. minIndex: minIndex,
  520. maxIndex: maxIndex
  521. };
  522. },
  523. /**
  524. * 添加provider到地图中
  525. * @param {Object} provider 图层构建器
  526. * @param {Object} layerId 图层Id
  527. */
  528. _addImageryProvider: function(provider, layerId) {
  529. var resSearch = this._searchCorrelationLayerIndex(layerId);
  530. var resLayer = undefined;
  531. if (resSearch != undefined && resSearch.maxIndex != -1) {
  532. /* 找到该图层顶部的关联图层 则直接插入到该图层到底部 */
  533. resLayer = this.imageryLayers.addImageryProvider(provider, resSearch.maxIndex);
  534. } else if (resSearch != undefined && resSearch.minIndex != -1 && resSearch.minIndex != this
  535. .imageryLayers.length - 1) {
  536. /* 找到该图层底部关联的图层 且该图层不是最顶部的图层 则将该图层加载到这个图层之上 */
  537. resLayer = this.imageryLayers.addImageryProvider(provider, resSearch.minIndex + 1);
  538. } else {
  539. resLayer = this.imageryLayers.addImageryProvider(provider);
  540. }
  541. return resLayer;
  542. },
  543. /**
  544. * @param {int} red 红色[0~255]
  545. * @param {int} green 绿色[0~255]
  546. * @param {int} blue 蓝色[0~255]
  547. * @param {int} alpha 透明度[0~1]
  548. */
  549. _toColor: function(red, green, blue, alpha) {
  550. return new Cesium.Color(red / 255.0, green / 255.0, blue / 255.0, alpha)
  551. },
  552. /**
  553. * 弧度转度
  554. * @param {float} arc 弧度
  555. */
  556. _arcToDegree: function(arc) {
  557. return arc / Math.PI * 180;
  558. },
  559. /**
  560. * 获取海拔高度等信息
  561. * @param {Object} screenPoint 屏幕点
  562. */
  563. _getHeightPoint: function(screenPoint) {
  564. var self = this;
  565. var viewer = this.viewer;
  566. var pick = new Cesium.Cartesian2(screenPoint.x, screenPoint.y);
  567. let resultPoint = {};
  568. if (pick) {
  569. //根据射线和场景求出在球面中的笛卡尔坐标
  570. var cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(pick), viewer.scene);
  571. //获取该浏览器坐标的顶部数据
  572. var feature = viewer.scene.pick(screenPoint);
  573. if (cartesian) {
  574. //世界坐标转地理坐标(弧度)
  575. var cartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(cartesian);
  576. if (cartographic) {
  577. //海拔
  578. var height = viewer.scene.globe.getHeight(cartographic);
  579. //视角海拔高度
  580. var he = Math.sqrt(viewer.scene.camera.positionWC.x * viewer.scene.camera.positionWC.x +
  581. viewer.scene.camera.positionWC.y * viewer.scene.camera.positionWC.y + viewer
  582. .scene.camera.positionWC.z * viewer.scene.camera.positionWC.z);
  583. var he2 = Math.sqrt(cartesian.x * cartesian.x + cartesian.y * cartesian.y + cartesian
  584. .z * cartesian.z);
  585. //地理坐标(弧度)转经纬度坐标
  586. var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI *
  587. 180
  588. ];
  589. if (!height) {
  590. height = 0;
  591. }
  592. if (!he) {
  593. he = 0;
  594. }
  595. if (!he2) {
  596. he2 = 0;
  597. }
  598. if (!point) {
  599. point = [0, 0];
  600. }
  601. resultPoint['x'] = point[0].toFixed(6); //经度
  602. resultPoint['y'] = point[0].toFixed(6); //纬度
  603. resultPoint['z'] = height.toFixed(1); //海拔
  604. resultPoint['m'] = (he - he2).toFixed(1); //视角(相机)高度
  605. resultPoint['h'] = height.toFixed(1); //建筑物海拔高度
  606. }
  607. }
  608. if (feature != undefined) {
  609. let cartesian = viewer.scene.pickPosition(screenPoint);
  610. if (Cesium.defined(cartesian)) {
  611. //如果对象已定义,将度转为经纬度
  612. let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  613. let lon = Cesium.Math.toDegrees(cartographic.longitude);
  614. let lat = Cesium.Math.toDegrees(cartographic.latitude);
  615. let MouseHeight = cartographic.height; //模型高度
  616. resultPoint['h'] = MouseHeight.toFixed(1);
  617. }
  618. }
  619. }
  620. return resultPoint;
  621. },
  622. /**
  623. * 三维模型旋转平移
  624. * @param {Object} tileset 三维模型数据
  625. * @param {JSON} params
  626. * params参数{tx:{float}x方向平移 ty:{float}y方向平移 tz:{float}z方向平移}
  627. * params参数{rx:{float}x方向旋转 ry:{float}y方向旋转 rz:{float}z方向旋转}
  628. */
  629. _update3dtilesMaxtrix: function(tileset, params) {
  630. //旋转
  631. var mx = Cesium.Matrix3.fromRotationX(Cesium.Math.toRadians(params.rx));
  632. var my = Cesium.Matrix3.fromRotationY(Cesium.Math.toRadians(params.ry));
  633. var mz = Cesium.Matrix3.fromRotationZ(Cesium.Math.toRadians(params.rz));
  634. var rotationX = Cesium.Matrix4.fromRotationTranslation(mx);
  635. var rotationY = Cesium.Matrix4.fromRotationTranslation(my);
  636. var rotationZ = Cesium.Matrix4.fromRotationTranslation(mz);
  637. //平移
  638. var position = Cesium.Cartesian3.fromDegrees(params.tx, params.ty, params.tz);
  639. var m = Cesium.Transforms.eastNorthUpToFixedFrame(position);
  640. //旋转、平移矩阵相乘
  641. Cesium.Matrix4.multiply(m, rotationX, m);
  642. Cesium.Matrix4.multiply(m, rotationY, m);
  643. Cesium.Matrix4.multiply(m, rotationZ, m);
  644. //赋值给tileset
  645. tileset._root.transform = m;
  646. },
  647. /**
  648. * 世界坐标系坐标转换为经纬度坐标
  649. * @param {Object} coord 世界坐标系坐标
  650. */
  651. _wordToWGS84: function(coord) {
  652. var g84 = Cesium.Ellipsoid.WGS84.cartesianToCartographic(coord);
  653. var lat = Cesium.Math.toDegrees(g84.latitude);
  654. var lng = Cesium.Math.toDegrees(g84.longitude);
  655. var alt = g84.height;
  656. return {
  657. lng: lng,
  658. lat: lat,
  659. alt: alt,
  660. }
  661. },
  662. _getDataUri: function(url, callback) {
  663. var image = new Image();
  664. image.onload = function() {
  665. var canvas = document.createElement('canvas');
  666. canvas.width = this.naturalWidth; // or 'width' if you want a special/scaled size
  667. canvas.height = this.naturalHeight; // or 'height' if you want a special/scaled size
  668. canvas.getContext('2d').drawImage(this, 0, 0);
  669. // Get raw image data
  670. callback(canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, ''));
  671. // ... or get as Data URI
  672. callback(canvas.toDataURL('image/png'));
  673. };
  674. image.src = url;
  675. },
  676. /**
  677. * 获取相机输出参数
  678. */
  679. _getCameraParameter: function() {
  680. var self = this;
  681. var position = this._getCameraPosition();
  682. return {
  683. screenX: '',
  684. screenY: '',
  685. mapX: position.lng.toFixed(6),
  686. mapY: position.lat.toFixed(6),
  687. mapZ: position.alt.toFixed(2),
  688. pitch: self._arcToDegree(self.viewer.camera.pitch),
  689. height: self.viewer.camera.positionCartographic.height,
  690. heading: self._arcToDegree(self.viewer.camera.heading),
  691. }
  692. },
  693. /**
  694. * 获取相机位置{lng: lat: alt:}
  695. */
  696. _getCameraPosition: function() {
  697. var ellipsoid = this.viewer.scene.globe.ellipsoid;
  698. var position = this.viewer.camera.position;
  699. var cartographic = ellipsoid.cartesianToCartographic(position);
  700. return {
  701. lng: this._arcToDegree(cartographic.longitude),
  702. lat: this._arcToDegree(cartographic.latitude),
  703. alt: cartographic.height,
  704. }
  705. },
  706. /**
  707. * 获取屏幕点的经纬度及高度 如果点击位置有模型则获取模型高度 否则获取地形高度
  708. * @param {JSON} screenPoint 屏幕点
  709. * x{float}:x位置
  710. * y{float}:y位置
  711. */
  712. _getLocation: function(screenPoint) {
  713. var lng = undefined,
  714. lat = undefined,
  715. height = undefined;
  716. /* 从相机位置到 windowPosition 处的像素创建射线在世界坐标系中 */
  717. var ray = this.viewer.scene.camera.getPickRay(screenPoint);
  718. /* 找到射线与渲染的地球表面之间的交点 */
  719. var position = this.viewer.scene.globe.pick(ray, this.viewer.scene);
  720. /* 获取地理位置的制图表达 */
  721. var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(position);
  722. /* 查询屏幕位置的要素 */
  723. var feature = this.viewer.scene.pick(screenPoint);
  724. if (feature == undefined) {
  725. lng = Cesium.Math.toDegrees(cartographic.longitude);
  726. lat = Cesium.Math.toDegrees(cartographic.latitude);
  727. height = cartographic.height;
  728. console.log("地形高度 = " + height);
  729. } else {
  730. var cartesian = this.viewer.scene.pickPosition(screenPoint);
  731. if (Cesium.defined(cartesian)) {
  732. var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  733. lng = Cesium.Math.toDegrees(cartographic.longitude);
  734. lat = Cesium.Math.toDegrees(cartographic.latitude);
  735. height = cartographic.height;
  736. console.log("三维高度 = " + height);
  737. }
  738. }
  739. /* 返回结果 */
  740. return {
  741. lng: lng,
  742. lat: lat,
  743. height: height,
  744. }
  745. }
  746. })
  747. /**
  748. * 图层相关
  749. */
  750. CrMap.prototype.extend({
  751. /**
  752. * 设置地形
  753. * @param {JSON} options
  754. * url{string}:地形服务URL地址
  755. */
  756. setTerrainLayer: function(options) {
  757. var terrainLayer = new Cesium.CesiumTerrainProvider({
  758. url: options.url, // 默认立体地表
  759. // 请求照明
  760. requestVertexNormals: true,
  761. // 请求水波纹效果
  762. requestWaterMask: true
  763. });
  764. this.viewer.terrainProvider = terrainLayer;
  765. /* 保存值公共变量 后期使用 */
  766. window['dem'] = terrainLayer;
  767. },
  768. /**
  769. * 添加Mapbox图层
  770. * @param {JSON} options
  771. * id{String}:图层Id
  772. * isshow{boolean}[true/false]:是否显示
  773. */
  774. addMapboxLayer: function(options) {
  775. this._consoleLayerInfo(options.index, options.id);
  776. var mapboxProvider = new Cesium.MapboxStyleImageryProvider({
  777. url: 'https://api.mapbox.com/styles/v1',
  778. username: 'chenchen1990',
  779. styleId: 'ckvgc14xrh7mo14qowdw4wrkf',
  780. accessToken: 'pk.eyJ1IjoiY2hlbmNoZW4xOTkwIiwiYSI6ImNrbzA3eTY1OTA3dXkyd20zdG40ZGdmNXYifQ.xWKxjBG6mEDh55_oln0nAg',
  781. scaleFactor: true
  782. });
  783. /* 加入图层 */
  784. var mapboxLayer = this._addImageryProvider(mapboxProvider, options.id);
  785. /* 控制是否显示 */
  786. mapboxLayer.show = options.isshow == undefined ? true : options.isshow;
  787. /* 加入到整体图层中 以便可以删除对应的图层 */
  788. window[options.id] = mapboxLayer;
  789. },
  790. /**
  791. * 添加在线影像地图
  792. * @param {JSON} options
  793. * id{string}:图层id
  794. * isshow{boolean}[true/false]:是否显示
  795. */
  796. addOnlineRasterLayer: function(options) {
  797. this._consoleLayerInfo(options.index, options.id);
  798. /* 加载影像图底图 */
  799. var tdtImageURL =
  800. "https://{s}.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=2471a323eac0646da7c7af7e16788b71";
  801. var tdtImageURLTemplate = new Cesium.UrlTemplateImageryProvider({
  802. url: tdtImageURL,
  803. tilingScheme: new Cesium.WebMercatorTilingScheme(),
  804. minimumLevel: 0,
  805. maximumLevel: 18,
  806. subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
  807. });
  808. var layerRaseter = this._addImageryProvider(tdtImageURLTemplate, options.id);
  809. layerRaseter.gamma = 0.5;
  810. layerRaseter.show = options.isshow == undefined ? true : options.isshow;
  811. /* 加载影像图标签 */
  812. var tdtImageLabelURL =
  813. "https://{s}.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=2471a323eac0646da7c7af7e16788b71";
  814. var tdtImageLabelURLTemplate = new Cesium.UrlTemplateImageryProvider({
  815. url: tdtImageLabelURL,
  816. tilingScheme: new Cesium.WebMercatorTilingScheme(),
  817. minimumLevel: 0,
  818. maximumLevel: 18,
  819. subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
  820. });
  821. /* 标注添加到最顶层 */
  822. var layerLabel = this.imageryLayers.addImageryProvider(tdtImageLabelURLTemplate);;
  823. layerLabel.show = options.isshow == undefined ? true : options.isshow;
  824. //查询标注图层索引 然后在其下方加载对应的图层
  825. var labelIndex = this.imageryLayers.indexOf(layerLabel);
  826. /* 加入到整体图层中 以便可以删除对应的图层 */
  827. window[options.id] = layerRaseter;
  828. window[options.id + labelFlag] = layerLabel;
  829. },
  830. /**
  831. * 添加在线标准地图
  832. * @param {JSON} options
  833. * id{string}:图层id
  834. * isshow{boolean}[true/false]:是否显示
  835. */
  836. addOnlineVectorLayer: function(options) {
  837. this._consoleLayerInfo(options.index, options.id);
  838. /* 加载矢量底图 */
  839. var tdtImageURL =
  840. "https://{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=2471a323eac0646da7c7af7e16788b71";
  841. var tdtImageURLTemplate = new Cesium.UrlTemplateImageryProvider({
  842. url: tdtImageURL,
  843. tilingScheme: new Cesium.WebMercatorTilingScheme(),
  844. minimumLevel: 0,
  845. maximumLevel: 18,
  846. subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
  847. });
  848. var layerVector = this._addImageryProvider(tdtImageURLTemplate, options.id);
  849. layerVector.gamma = 0.1;
  850. layerVector.show = options.isshow == undefined ? true : options.isshow;
  851. //首先添加标注图层
  852. var tdtImageLabelURL =
  853. "https://{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=2471a323eac0646da7c7af7e16788b71";
  854. var tdtImageLabelURLTemplate = new Cesium.UrlTemplateImageryProvider({
  855. url: tdtImageLabelURL,
  856. tilingScheme: new Cesium.WebMercatorTilingScheme(),
  857. minimumLevel: 0,
  858. maximumLevel: 18,
  859. subdomains: ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
  860. });
  861. var layerLabel = this.imageryLayers.addImageryProvider(tdtImageLabelURLTemplate);
  862. layerLabel.gamma = 0.2;
  863. layerLabel.show = options.isshow == undefined ? true : options.isshow;
  864. /* 加入到整体图层中 以便可以删除对应的图层 */
  865. window[options.id] = layerVector;
  866. window[options.id + labelFlag] = layerLabel;
  867. },
  868. /**
  869. * @param {JSON} options
  870. * url{string}:wmts服务地址
  871. * maxLevel{int}:最大缩放层级
  872. * minLevel{int}:最小缩放层级
  873. * isshow{boolean}[true/false]:是否显示
  874. * alpha{float}[0.0-1.0]:透明度
  875. */
  876. addWmtsTileLayer: function(options) {
  877. this._consoleLayerInfo(options.index, options.id);
  878. var wmtsProvider = new Cesium.WebMapTileServiceImageryProvider({
  879. url: options.url,
  880. layer: 1,
  881. style: 'default',
  882. format: 'image/png',
  883. tileMatrixSetID: 'default028mm',
  884. maximumLevel: options.maxLevel,
  885. minimumLevel: options.minLevel,
  886. });
  887. var wmtslayer = this._addImageryProvider(wmtsProvider, options.id);
  888. wmtslayer.show = options.isshow == undefined ? true : options.isshow;
  889. /*加入到窗体中*/
  890. window[options.id] = wmtslayer;
  891. window[options.id].alpha = options.alpha == undefined ? 1.0 : parseFloat(options.alpha);
  892. },
  893. /**
  894. * 加载ArcGIS矢量图层
  895. * @param {JSON} options 参数集合
  896. * id{string}:图层Id 唯一标识
  897. * url{string}:服务地址
  898. * layers{array}:图层数组 [0]
  899. * isshow{boolean}[true/false]:是否显示
  900. * isQuery{boolean}[true/false]:是否支持查询
  901. * label{JSON}:标注配置
  902. * url{string}:标注地址
  903. * lng{string}:标注位置的经度字段名称
  904. * lat{string}:标注位置的纬度字段名称
  905. * alt{string}:标注位置的高度字段名称
  906. * key{string}:标注显示内容的字段名称
  907. * size{int}:标注的大小 单位是px 无需带px
  908. * family{string}:标注的字体名称
  909. * color{string}:标注的颜色,为使用逗号分隔开的字符串 233,124,234
  910. * display{int}:标注的显示距离
  911. * image{string}:标注关联的广告牌路径
  912. */
  913. addAGSVectorServer: function(options) {
  914. this._consoleLayerInfo(options.index, options.id);
  915. var self = this;
  916. self._queryAGServerExtent(options.url, options.layers[0], function(data) {
  917. var gisProvider = new Cesium.ArcGisMapServerImageryProvider({
  918. url: options.url,
  919. layers: options.layers,
  920. rectangle: Cesium.Rectangle.fromDegrees(data.xmin, data.ymin, data.xmax,
  921. data.ymax),
  922. });
  923. //添加到图层中
  924. var layer = self._addImageryProvider(gisProvider, options.id);
  925. layer.show = options.isshow == undefined ? true : options.isshow; //控制是否显示
  926. //判断是否需要加入到查询数组
  927. if (options.isQuery != undefined && options.isQuery) {
  928. //判断是否已经存在
  929. var isExists = false;
  930. for (var qIdx = 0; qIdx < self.queryLayers.length; qIdx++) {
  931. if (self.queryLayers[qIdx].id == options.id) {
  932. isExists = true;
  933. break;
  934. }
  935. }
  936. if (!isExists) {
  937. self.queryLayers.push({
  938. id: options.id,
  939. provider: gisProvider,
  940. });
  941. }
  942. }
  943. if (options.label != undefined) {
  944. var queryFields = options.label.lat + "," + options.label.lng + "," + options
  945. .label
  946. .alt + "," + options.label.key;
  947. //追加属性 如果是多图片显示
  948. if (options.label.images != undefined) {
  949. queryFields += "," + options.label.images.key;
  950. }
  951. //如果存在移动弹出信息 则对查询字段进行组合
  952. var entityTooltip = options.label.tooltip;
  953. if (entityTooltip != undefined) {
  954. queryFields += "," + entityTooltip.key + "," + entityTooltip.fields.join();
  955. }
  956. self._queryArcGISGeoJSON({
  957. url: options.label.url,
  958. fields: queryFields,
  959. }, function(resData) {
  960. var parentEntity = self.viewer.entities.add(new Cesium.Entity({
  961. name: options.id,
  962. }));
  963. parentEntity.show = options.isshow == undefined ? true : options
  964. .isshow; //设置是否显示
  965. //查询结束 开始添加标注
  966. for (var i = 0; i < resData.features.length; i++) {
  967. var lng = resData.features[i].attributes[options.label.lng];
  968. var lat = resData.features[i].attributes[options.label.lat];
  969. var alt = resData.features[i].attributes[options.label.alt];
  970. var key = resData.features[i].attributes[options.label.key];
  971. var entity = self.viewer.entities.add({
  972. name: options.id,
  973. parent: parentEntity,
  974. position: Cesium.Cartesian3.fromDegrees(lng, lat,
  975. parseFloat(alt) + 50),
  976. label: {
  977. text: key,
  978. font: options.label.size + 'px ' + options.label
  979. .family,
  980. scale: 0.5,
  981. fillColor: Cesium.Color.WHITE,
  982. outlineColor: Cesium.Color.fromCssColorString(
  983. 'rgba(' + options.label.color + ')'),
  984. outlineWidth: 4,
  985. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  986. horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
  987. verticalOrigin: Cesium.VerticalOrigin.center,
  988. pixelOffset: new Cesium.Cartesian2(20, 0),
  989. showBackground: false,
  990. backgroundColor: new Cesium.Color(0.5, 0.6, 1,
  991. 0.5),
  992. distanceDisplayCondition: new Cesium
  993. .DistanceDisplayCondition(0, options.label
  994. .display),
  995. },
  996. billboard: {
  997. image: self.serverUrl + options.label.image,
  998. horizontalOrigin: Cesium.HorizontalOrigin
  999. .center,
  1000. verticalOrigin: Cesium.VerticalOrigin.center,
  1001. scale: 0.5,
  1002. }
  1003. });
  1004. //如果是多图片显示 则重置entity的广告牌图片
  1005. if (options.label.images != undefined) {
  1006. var value = resData.features[i].attributes[options.label
  1007. .images
  1008. .key];
  1009. var config = options.label.images.config;
  1010. for (var idx = 0; idx < config.length; idx++) {
  1011. var minValue = config[idx].minValue;
  1012. var maxValue = config[idx].maxValue;
  1013. if (value >= minValue && value <= maxValue) {
  1014. entity.billboard.image = config[idx].icon;
  1015. break;
  1016. }
  1017. }
  1018. }
  1019. //加入实体
  1020. //组合弹出信息
  1021. if (entityTooltip != undefined) {
  1022. var htmlJSON = {};
  1023. htmlJSON['key'] = resData.features[i].attributes[
  1024. entityTooltip
  1025. .key];
  1026. for (var fld = 0; fld < entityTooltip.fields
  1027. .length; fld++) {
  1028. htmlJSON[entityTooltip.fields[fld]] = resData.features[
  1029. i]
  1030. .attributes[entityTooltip.fields[fld]];
  1031. }
  1032. entity.tooltip = {
  1033. html: JSON.stringify(htmlJSON),
  1034. anchor: [0, 30],
  1035. }
  1036. }
  1037. }
  1038. window[options.id] = layer;
  1039. window[options.id + labelFlag] = parentEntity;
  1040. });
  1041. } else {
  1042. window[options.id] = layer;
  1043. }
  1044. }, function(err) {
  1045. });
  1046. },
  1047. /**
  1048. * 加载ArcGIS矢量图层
  1049. * @param {JSON} options 参数集合
  1050. * id{string}:图层Id 唯一标识
  1051. * url{string}:服务地址
  1052. * layers{array}:图层数组 [0]
  1053. * isshow{boolean}[true/false]:是否显示
  1054. * isQuery{boolean}[true/false]:是否支持查询
  1055. * label{JSON}:标注配置
  1056. * url{string}:标注地址
  1057. * lng{string}:标注位置的经度字段名称
  1058. * lat{string}:标注位置的纬度字段名称
  1059. * alt{string}:标注位置的高度字段名称
  1060. * key{string}:标注显示内容的字段名称
  1061. * size{int}:标注的大小 单位是px 无需带px
  1062. * family{string}:标注的字体名称
  1063. * color{string}:标注的颜色,为使用逗号分隔开的字符串 233,124,234
  1064. * display{int}:标注的显示距离
  1065. * offset{array}:标注的偏移距离[0,0]
  1066. * scale{float}:标注的显示比例
  1067. * billboard{JSON}:广告牌配置
  1068. * image{string}:关联的广告牌路径
  1069. * display{int}:广告牌的显示距离
  1070. * offset{array}:广告牌的偏移距离[0,0]
  1071. * scale{float}:广告牌的显示比例
  1072. */
  1073. addAGSVectorServerToo: function(options) {
  1074. this._consoleLayerInfo(options.index, options.id);
  1075. var self = this;
  1076. self._queryAGServerExtent(options.url, options.layers[0], function(data) {
  1077. var gisProvider = new Cesium.ArcGisMapServerImageryProvider({
  1078. url: options.url,
  1079. layers: options.layers,
  1080. rectangle: Cesium.Rectangle.fromDegrees(data.xmin, data.ymin, data.xmax,
  1081. data.ymax),
  1082. });
  1083. //添加到图层中
  1084. var layer = self._addImageryProvider(gisProvider, options.id);
  1085. layer.show = options.isshow == undefined ? true : options.isshow; //控制是否显示
  1086. //判断是否需要加入到查询数组
  1087. if (options.isQuery != undefined && options.isQuery) {
  1088. //判断是否已经存在
  1089. var isExists = false;
  1090. for (var qIdx = 0; qIdx < self.queryLayers.length; qIdx++) {
  1091. if (self.queryLayers[qIdx].id == options.id) {
  1092. isExists = true;
  1093. break;
  1094. }
  1095. }
  1096. if (!isExists) {
  1097. self.queryLayers.push({
  1098. id: options.id,
  1099. provider: gisProvider,
  1100. });
  1101. }
  1102. }
  1103. if (options.label != undefined) {
  1104. var queryFields = options.label.lat + "," + options.label.lng + "," + options
  1105. .label
  1106. .alt + "," + options.label.key;
  1107. //如果存在移动弹出信息 则对查询字段进行组合
  1108. var entityTooltip = options.label.tooltip;
  1109. if (entityTooltip != undefined) {
  1110. queryFields += "," + entityTooltip.key + "," + entityTooltip.fields.join();
  1111. }
  1112. self._queryArcGISGeoJSON({
  1113. url: options.label.url,
  1114. fields: queryFields,
  1115. }, function(resData) {
  1116. var parentEntity = self.viewer.entities.add(new Cesium.Entity({
  1117. name: options.id,
  1118. }));
  1119. parentEntity.show = options.isshow == undefined ? true : options
  1120. .isshow; //设置是否显示
  1121. //查询结束 开始添加标注
  1122. for (var i = 0; i < resData.features.length; i++) {
  1123. var lng = resData.features[i].attributes[options.label.lng];
  1124. var lat = resData.features[i].attributes[options.label.lat];
  1125. var alt = resData.features[i].attributes[options.label.alt];
  1126. var key = resData.features[i].attributes[options.label.key];
  1127. var entity = self.viewer.entities.add({
  1128. name: options.id,
  1129. parent: parentEntity,
  1130. position: Cesium.Cartesian3.fromDegrees(lng, lat,
  1131. parseFloat(alt) - 0),
  1132. label: {
  1133. text: key,
  1134. font: options.label.size + 'px ' + options.label
  1135. .family,
  1136. scale: options.label.scale,
  1137. fillColor: Cesium.Color.fromCssColorString(
  1138. 'rgba(' + options.label.color + ')'),
  1139. horizontalOrigin: Cesium.HorizontalOrigin
  1140. .CENTER,
  1141. verticalOrigin: Cesium.VerticalOrigin.CENTER,
  1142. pixelOffset: new Cesium.Cartesian2(options.label
  1143. .offset[0], options.label.offset[1]),
  1144. distanceDisplayCondition: new Cesium
  1145. .DistanceDisplayCondition(0, options.label
  1146. .display),
  1147. eyeOffset: new Cesium.Cartesian3(0, 0, -10)
  1148. }
  1149. });
  1150. if (options.billboard != undefined) {
  1151. entity.billboard = {
  1152. image: options.billboard.image,
  1153. horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  1154. scale: options.billboard.scale,
  1155. verticalOrigin: Cesium.VerticalOrigin.BASELINE,
  1156. pixelOffset: new Cesium.Cartesian2(options.billboard
  1157. .offset[0], options.billboard.offset[1]),
  1158. distanceDisplayCondition: new Cesium
  1159. .DistanceDisplayCondition(0, options.billboard
  1160. .display),
  1161. }
  1162. }
  1163. //组合弹出信息
  1164. if (entityTooltip != undefined) {
  1165. var htmlJSON = {};
  1166. htmlJSON['key'] = resData.features[i].attributes[
  1167. entityTooltip
  1168. .key];
  1169. for (var fld = 0; fld < entityTooltip.fields
  1170. .length; fld++) {
  1171. htmlJSON[entityTooltip.fields[fld]] = resData.features[
  1172. i]
  1173. .attributes[entityTooltip.fields[fld]];
  1174. }
  1175. entity.tooltip = {
  1176. html: JSON.stringify(htmlJSON),
  1177. anchor: [0, 30],
  1178. }
  1179. }
  1180. }
  1181. window[options.id] = layer;
  1182. window[options.id + labelFlag] = parentEntity;
  1183. });
  1184. } else {
  1185. window[options.id] = layer;
  1186. }
  1187. }, function(err) {
  1188. });
  1189. },
  1190. /**
  1191. * @param {JSON} options
  1192. * url[{string}]:资源的Url数组
  1193. * id{string}:图层Id
  1194. * isshow{boolean}[true/false]:是否显示
  1195. * params参数{tx:{float}x方向平移 ty:{float}y方向平移 tz:{float}z方向平移}
  1196. * params参数{rx:{float}x方向旋转 ry:{float}y方向旋转 rz:{float}z方向旋转}
  1197. */
  1198. add3DTilesets: function(options) {
  1199. var self = this;
  1200. var subLayerIds = [];
  1201. var tilesets = new Cesium.PrimitiveCollection();
  1202. for (var i = 0; i < options.url.length; i++) {
  1203. var url = options.url[i];
  1204. var tileLayer = new Cesium.Cesium3DTileset({
  1205. url: url,
  1206. show: options.isshow == undefined ? true : options.isshow,
  1207. maximumScreenSpaceError: 16,
  1208. maxmumMemoryUsage: 218,
  1209. skipScreenSpaceErrorFactor: 16,
  1210. dynamicScreenSpaceError: true,
  1211. skipLevels: 1,
  1212. cullWithChildrenBounds: true,
  1213. cullRequestsWhileMoving: true,
  1214. cullRequestsWhileMovingMultiplier: 10, // 值越小能够更快的剔除
  1215. });
  1216. var tileset = tilesets.add(tileLayer);
  1217. tileset.readyPromise.then(function(primitive) {
  1218. if (options.params != undefined) {
  1219. self._update3dtilesMaxtrix(primitive, options.params);
  1220. }
  1221. })
  1222. }
  1223. /* 加入图层 */
  1224. this.primitives.add(tilesets);
  1225. /* 加入公共资源 */
  1226. window[options.id] = tilesets;
  1227. },
  1228. /**
  1229. * @param {JSON} options
  1230. * id{string}:图层Id
  1231. * isshow{boolean}[true/false]:是否显示
  1232. * model{JSON数组}[{url:glb地址,lng:lat:alt:},{}] 加载的glb文件JSON格式数组
  1233. */
  1234. addGlbs: function(options) {
  1235. /* 如果没有配置模型则返回 */
  1236. if (options.model == undefined || options.model.length == 0) rturn;
  1237. var self = this;
  1238. var layer = undefined;
  1239. /* 创建第0个glb 作为飞行点 */
  1240. var model0 = options.model[0];
  1241. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
  1242. Cesium.Cartesian3.fromDegrees(model0.lng, model0.lat, model0.alt)
  1243. );
  1244. var parentEntity = self.entities.add({
  1245. name: options.id,
  1246. position: Cesium.Cartesian3.fromDegrees(model0.lng, model0.lat, model0.alt),
  1247. model: {
  1248. uri: model0.name,
  1249. modelMatrix: modelMatrix,
  1250. scale: 1.0 //放大倍数
  1251. },
  1252. });
  1253. /* 设置显示或隐藏 */
  1254. parentEntity.show = options.isshow == undefined ? true : options.isshow;
  1255. /* 挂接其他大棚 */
  1256. for (var i = 1; i < options.model.length; i++) {
  1257. var model = options.model[i];
  1258. var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
  1259. Cesium.Cartesian3.fromDegrees(model.lng, model.lat, model.alt)
  1260. );
  1261. //做个实验试试
  1262. var entity = self.entities.add({
  1263. parent: parentEntity,
  1264. name: options.id,
  1265. position: Cesium.Cartesian3.fromDegrees(model.lng, model.lat, model.alt),
  1266. model: {
  1267. uri: model.name,
  1268. modelMatrix: modelMatrix,
  1269. scale: 1.0 //放大倍数
  1270. },
  1271. });
  1272. }
  1273. /* 加入到全局*/
  1274. window[options.id] = parentEntity;
  1275. },
  1276. /**
  1277. * 添加GeoJSON数据图层
  1278. * @param {JSON} options 配置项
  1279. * url{String}:数据地址
  1280. * line{JSON}:线的配置
  1281. * line.width{int}宽度
  1282. * line.power{double}[0-1]:发光强度
  1283. * line.color{}
  1284. */
  1285. addGeoJSONLayer: function(options) {
  1286. var self = this;
  1287. /* 加载JSON数据 */
  1288. var promise = Cesium.GeoJsonDataSource.load(options.url, {
  1289. clampToGround: true,
  1290. });
  1291. promise.then(function(dataSource) {
  1292. /* 设置数据源的名称 */
  1293. dataSource.name = options.id;
  1294. /* 添加数据源 */
  1295. self.dataSources.add(dataSource);
  1296. var entities = dataSource.entities.values;
  1297. var lineWidth = 20;
  1298. var linePower = 0.2;
  1299. var lineColor = Cesium.Color.ORANGERED.withAlpha(.9);
  1300. /* 根据配置项判断是否进行了相关设置 */
  1301. if (options.line != undefined) {
  1302. if (options.line.width != undefined) lineWidth = options.line.width;
  1303. if (options.line.power != undefined) linePower = options.line.power;
  1304. if (options.line.color != undefined) {
  1305. var jsonColor = options.line.color;
  1306. if (jsonColor.r != undefined && jsonColor.g != undefined && jsonColor.b !=
  1307. undefined && jsonColor.a != undefined) {
  1308. lineColor = self._toColor(jsonColor.r, jsonColor.g, jsonColor.b,
  1309. jsonColor
  1310. .a);
  1311. }
  1312. }
  1313. }
  1314. for (var o = 0; o < entities.length; o++) {
  1315. var entity = entities[o];
  1316. entity.nameID = o; //给每条线添加一个编号,方便之后对线修改样式
  1317. entity.polyline.width = lineWidth; //添加默认样式
  1318. (entity.polyline.material = new Cesium.PolylineGlowMaterialProperty({
  1319. glowPower: linePower, //一个数字属性,指定发光强度,占总线宽的百分比。
  1320. color: lineColor,
  1321. }), 10)
  1322. }
  1323. /* 加入到全局 */
  1324. window[options.id] = dataSource;
  1325. })
  1326. },
  1327. /**
  1328. * 从服务中根据范围查询要素并添加到地图图层中
  1329. * @param {JSON} options
  1330. * geometry{String}:坐标字符串,使用逗号分隔
  1331. * fields{String}:输出字段,如果输出全部,可不输出,字段之间使用逗号分隔
  1332. * @param {Function(JSON)} callSuccess 成功回调
  1333. * @param {Function(String)} callError 失败回调
  1334. */
  1335. addFeaturesFromServerByPolygon: function(options,callSuccess,callError) {
  1336. this._queryArcGISGeoJSON({
  1337. geometry: options.geometry,
  1338. geometryType: options.geometryType == 'polygon'?'esriGeometryPolygon':'esriGeometryEnvelope',
  1339. fields: options.fields == undefined ? "*" : options.fields,
  1340. returnGeometry: true,
  1341. url: options.url
  1342. }, function(resData) {
  1343. if(callSuccess != undefined) callSuccess(resData);
  1344. }, function(err) {
  1345. if(callError != undefined) callError(err);
  1346. });
  1347. },
  1348. /**
  1349. * 删除加载的所有图层
  1350. */
  1351. removeAllLayer: function() {
  1352. this.imageryLayers.removeAll();
  1353. this.viewer.entities.removeAll();
  1354. this.viewer.scene.primitives.removeAll();
  1355. this.queryLayers = [];
  1356. this.dataSources.removeAll();
  1357. },
  1358. /**
  1359. * 移除图层
  1360. * @param {Object} layerId 图层Id
  1361. */
  1362. removeLayer: function(layerId) {
  1363. this.imageryLayers.remove(window[layerId]);
  1364. this.primitives.remove(window[layerId]);
  1365. this.dataSources.remove(window[layerId]);
  1366. /* 如果标注层存在则同步删除 */
  1367. if (window[layerId + labelFlag] != undefined) {
  1368. this.imageryLayers.remove(window[layerId + labelFlag]);
  1369. var entities = this.viewer.entities;
  1370. var delEntitys = [];
  1371. //循环查找符合条件的Entity
  1372. for (var i = 0; i < entities.values.length; i++) {
  1373. if (entities.values[i].name == layerId) {
  1374. delEntitys.push(entities.values[i]);
  1375. }
  1376. }
  1377. //删除符合条件的Entity
  1378. for (var i = 0; i < delEntitys.length; i++) {
  1379. entities.remove(delEntitys[i]);
  1380. }
  1381. }
  1382. /* 如果该图层是Entity 则根据名称判断是否需要删除 */
  1383. if (window[layerId] instanceof Cesium.Entity) {
  1384. var entities = this.viewer.entities;
  1385. var delEntitys = [];
  1386. //循环查找符合条件的Entity
  1387. for (var i = 0; i < entities.values.length; i++) {
  1388. if (entities.values[i].name == layerId) {
  1389. delEntitys.push(entities.values[i]);
  1390. }
  1391. }
  1392. //删除符合条件的Entity
  1393. for (var i = 0; i < delEntitys.length; i++) {
  1394. entities.remove(delEntitys[i]);
  1395. }
  1396. }
  1397. /* 如果图层可查询 则移除 */
  1398. for (var i = 0; i < this.queryLayers.length; i++) {
  1399. var qConfig = this.queryLayers[i];
  1400. if (qConfig.id == layerId) {
  1401. this.queryLayers.splice(i, 1);
  1402. }
  1403. }
  1404. },
  1405. })
  1406. /**
  1407. * 图斑标注相关
  1408. */
  1409. CrMap.prototype.extend({
  1410. /**
  1411. * @param {JSON} options 配置项
  1412. */
  1413. addCaseLabel: function(options) {
  1414. var self = this;
  1415. var longitude = parseFloat(options.lng);
  1416. var latitude = parseFloat(options.lat);
  1417. var altitude = parseFloat(options.alt);
  1418. this.caseLabels.add({
  1419. position: new Cesium.Cartesian3.fromDegrees(longitude, latitude, altitude),
  1420. text: options.text,
  1421. font: '22px SansCN-Normal',
  1422. fillColor: Cesium.Color.WHITE,
  1423. outlineColor: self._toColor(11, 48, 115, 1.0),
  1424. outlineWidth: 2,
  1425. horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  1426. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  1427. verticalOrigin: Cesium.VerticalOrigin.CENTER,
  1428. distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
  1429. heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
  1430. eyeOffset: new Cesium.Cartesian3(0, 0, -10),
  1431. pixelOffset: new Cesium.Cartesian2(10, -50),
  1432. scale: 0.45
  1433. });
  1434. this.caseLabelBillboards.add({
  1435. position: new Cesium.Cartesian3.fromDegrees(longitude, latitude, altitude),
  1436. image: self.serverUrl + options.image,
  1437. distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000),
  1438. heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
  1439. scale: 0.5,
  1440. horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  1441. verticalOrigin: Cesium.VerticalOrigin.BASELINE,
  1442. });
  1443. /* 刷祯 */
  1444. this.updateSence();
  1445. },
  1446. /**
  1447. * 删除全部图斑标注
  1448. */
  1449. removeAllCaseLabel: function() {
  1450. var self = this;
  1451. return new Promise((resolve, reject) => {
  1452. self.caseLabels.removeAll();
  1453. self.caseLabelBillboards.removeAll();
  1454. resolve(true);
  1455. });
  1456. },
  1457. /**
  1458. * 添加当前可视区域
  1459. * @param {JSON} options 配置项
  1460. * strLng{double}:矩形起始点经度
  1461. * strLat{double}:矩形起始点纬度
  1462. * endLng{double}:矩形终止点经度
  1463. * endLat{double}:矩形终止点纬度
  1464. */
  1465. addAreaRectangle: function(options) {
  1466. var self = this;
  1467. this.entities.removeById('areaRectangle');
  1468. var extent = Cesium.Rectangle.fromDegrees(options.strLng, options.strLat, options.endLng,
  1469. options
  1470. .endLat);
  1471. var flyRectangle = this.entities.add({
  1472. id: 'areaRectangle',
  1473. name: 'areaRectangle',
  1474. rectangle: {
  1475. coordinates: extent,
  1476. material: Cesium.Color.GREEN.withAlpha(0.6),
  1477. height: 10.0,
  1478. outline: false
  1479. }
  1480. });
  1481. },
  1482. /**
  1483. * 计算高程
  1484. * @param {JSON} options 配置项
  1485. * points{Array[JSON(lng,lat),...]}:点数组JSON
  1486. * success{function}:成功回调函数
  1487. */
  1488. calculateAltitude: function(options) {
  1489. var positions = [];
  1490. var points = options.points;
  1491. /* 构建点位置集合 */
  1492. for (var i = 0; i < points.length; i++) {
  1493. var point = points[i];
  1494. positions.push(Cesium.Cartographic.fromDegrees(parseFloat(point.lng), parseFloat(point
  1495. .lat)));
  1496. }
  1497. /* 构建查询 */
  1498. var promise = Cesium.sampleTerrain(window['dem'], 14, positions);
  1499. /* 监听查询完成 */
  1500. Cesium.when(promise, function(resData) {
  1501. var outHeights = [];
  1502. for (var i = 0; i < resData.length; i++) {
  1503. outHeights.push(resData[i].height);
  1504. }
  1505. if (options.success != undefined) options.success(outHeights);
  1506. });
  1507. }
  1508. });
  1509. /**
  1510. * 切割相关
  1511. */
  1512. CrMap.prototype.extend({
  1513. /**
  1514. * 动态改变ClippingPlane距离原点的距离
  1515. * @param {Object} plane ClippingPlane实例
  1516. */
  1517. _createPlaneUpdateFunction: function(plane) {
  1518. var self = this;
  1519. return function() {
  1520. plane.distance = self.planeTargetY + 10;
  1521. return plane;
  1522. };
  1523. },
  1524. /**
  1525. * 开始切割BIM
  1526. * @param {Object} tilesetId BIM模型图层Id
  1527. * @param {String} callback 消息回调
  1528. */
  1529. openClipBIM: function(tilesetId, callback) {
  1530. var self = this;
  1531. //self.planeTargetY = 30;
  1532. var tileset = window[tilesetId];
  1533. if (tileset == undefined) {
  1534. if (callback != undefined) {
  1535. callback("先开启BIM图层!");
  1536. }
  1537. } else {
  1538. var boundingSphere = tileset.get(0).boundingSphere;
  1539. var clippingPlanes = new Cesium.ClippingPlaneCollection({
  1540. planes: [
  1541. new Cesium.ClippingPlane(new Cesium.Cartesian3(0, 0, -1),
  1542. 30) // 平面的方向 以及 平面到原点的距离
  1543. ],
  1544. edgeColor: Cesium.Color.WHITE, // 平面切割时模型的边缘颜色
  1545. edgeWidth: 3.0 // 平面切割时模型的边缘宽度
  1546. });
  1547. tileset.get(0).clippingPlanes = clippingPlanes; //设置可以切割
  1548. var radius = boundingSphere.radius; // 长度
  1549. for (var i = 0; i < clippingPlanes.length; ++i) {
  1550. var plane = clippingPlanes.get(i);
  1551. self.viewer.entities.add({
  1552. name: 'entity_clip_bim',
  1553. position: boundingSphere.center,
  1554. plane: {
  1555. dimensions: new Cesium.Cartesian2(radius, radius),
  1556. material: Cesium.Color.RED.withAlpha(0.1),
  1557. plane: new Cesium.CallbackProperty(self._createPlaneUpdateFunction(
  1558. plane),
  1559. false),
  1560. outline: true,
  1561. outlineColor: Cesium.Color.WHITE
  1562. }
  1563. });
  1564. }
  1565. /* 缩放到位置 */
  1566. self.flyTo(tileset);
  1567. }
  1568. },
  1569. /**
  1570. * 关闭BIM切割
  1571. */
  1572. closeClipBIM: function() {
  1573. var name = 'entity_clip_bim';
  1574. var entities = this.viewer.entities;
  1575. var delEntitys = [];
  1576. //循环查找符合条件的Entity
  1577. for (var i = 0; i < entities.values.length; i++) {
  1578. if (entities.values[i].name == name) {
  1579. delEntitys.push(entities.values[i]);
  1580. }
  1581. }
  1582. //删除符合条件的Entity
  1583. for (var i = 0; i < delEntitys.length; i++) {
  1584. entities.remove(delEntitys[i]);
  1585. }
  1586. }
  1587. });
  1588. /**
  1589. * 工具相关
  1590. */
  1591. CrMap.prototype.extend({
  1592. /**
  1593. * 刷新场景 刷新一帧
  1594. */
  1595. updateSence: function() {
  1596. this.viewer.scene.requestRender();
  1597. },
  1598. /**
  1599. * 飞行至指定位置
  1600. * @param {double} longitude 经度
  1601. * @param {double} latitude 纬度
  1602. * @param {double} altitude 高度
  1603. */
  1604. zoomTo: function(longitude, latitude, altitude) {
  1605. var boundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(longitude,
  1606. latitude,
  1607. 0), altitude /
  1608. 3);
  1609. this.viewer.camera.flyToBoundingSphere(boundingSphere);
  1610. },
  1611. /**
  1612. * 飞行至指定对象
  1613. * @param {Object} obj 对象
  1614. */
  1615. flyTo: function(obj) {
  1616. if (obj instanceof Cesium.PrimitiveCollection) {
  1617. obj = obj.get(0);
  1618. }
  1619. this.viewer.flyTo(obj, {
  1620. offset: new Cesium.HeadingPitchRange(0.0, Cesium.Math.toRadians(-45.0)),
  1621. });
  1622. },
  1623. /**
  1624. * 相机视角飞行到指定位置
  1625. * @param {JSON} options 位置信息
  1626. * {lng: lat: alt: heading: pitch:}
  1627. */
  1628. flyToo: function(options) {
  1629. this.viewer.camera.flyTo({
  1630. destination: Cesium.Cartesian3.fromDegrees(options.lng, options.lat, options.alt),
  1631. orientation: {
  1632. heading: Cesium.Math.toRadians(options.heading, 0),
  1633. pitch: Cesium.Math.toRadians(options.pitch),
  1634. roll: 0.0
  1635. },
  1636. duration: options.duration == undefined ? 10 : options.duration,
  1637. complete: function() {
  1638. if (options.success != undefined) options.success();
  1639. },
  1640. })
  1641. },
  1642. /**
  1643. * 添加图层Id到初始化集合中
  1644. * @param {Object} layerId 图层Id
  1645. */
  1646. addBeforeLayerId: function(layerId) {
  1647. this.beforeLayerIds.push(layerId);
  1648. },
  1649. /**
  1650. * 设置地图在当前窗口中心点和高度下指北
  1651. */
  1652. setMapNorth: function() {
  1653. var height = Math.ceil(this.viewer.camera.positionCartographic.height);
  1654. var result = this.viewer.camera.pickEllipsoid(new Cesium.Cartesian2(this.viewer.canvas
  1655. .clientWidth /
  1656. 2, this.viewer
  1657. .canvas.clientHeight / 2));
  1658. var curPosition = Cesium.Ellipsoid.WGS84.cartesianToCartographic(result);
  1659. var lon = curPosition.longitude * 180 / Math.PI;
  1660. var lat = curPosition.latitude * 180 / Math.PI;
  1661. var boundingSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.fromDegrees(lon, lat, 0),
  1662. height /
  1663. 3);
  1664. this.viewer.camera.flyToBoundingSphere(boundingSphere);
  1665. },
  1666. /**
  1667. * 经纬度转换为屏幕坐标
  1668. * @param {JSON} point 坐标点
  1669. * point格式{lng: lat: alt:}
  1670. */
  1671. wgs84ToScreen: function(point) {
  1672. var position = Cesium.Cartesian3.fromDegrees(point.lng, point.lat, point.alt);
  1673. var res = Cesium.SceneTransforms.wgs84ToWindowCoordinates(this.viewer.scene, position);
  1674. if (res == undefined) {
  1675. return {
  1676. x: -500,
  1677. y: -500,
  1678. }
  1679. } else {
  1680. return {
  1681. x: res.x - 0,
  1682. y: res.y - 0,
  1683. };
  1684. }
  1685. },
  1686. /**
  1687. * 输出当前相机视角参数
  1688. */
  1689. exportCameraViewParams: function() {
  1690. var self = this;
  1691. var g84Position = self._wordToWGS84(self.viewer.camera.position)
  1692. var result = {
  1693. lng: g84Position.lng,
  1694. lat: g84Position.lat,
  1695. alt: g84Position.alt,
  1696. pitch: self._arcToDegree(self.viewer.camera.pitch),
  1697. heading: self._arcToDegree(self.viewer.camera.heading),
  1698. }
  1699. return result;
  1700. },
  1701. /**
  1702. * 计算当前位置距离相机的空间距离
  1703. * @param {Object} options 位置
  1704. * {lng: lat: alt:}
  1705. */
  1706. calculationToCameraDistance: function(options) {
  1707. var self = this;
  1708. var cameraPosition = self.viewer.camera.position;
  1709. var wgs84Position = Cesium.Cartographic.fromDegrees(options.lng, options.lat, options.alt);
  1710. var pointPosition = self.viewer.scene.globe.ellipsoid.cartographicToCartesian(wgs84Position);
  1711. /* 开始计算距离 */
  1712. var dx = cameraPosition.x - pointPosition.x;
  1713. var dy = cameraPosition.y - pointPosition.y;
  1714. var dz = cameraPosition.z - pointPosition.z;
  1715. return Math.sqrt(dx * dx + dy * dy + dz * dz);
  1716. },
  1717. /**
  1718. * 相机飞行位置
  1719. * @param {Object} options 设置项
  1720. * {lng:经度 lat:纬度 alt:高度}
  1721. */
  1722. flyCameraTo: function(options) {
  1723. alert(options.lng + "," + options.lat + "," + options.alt)
  1724. var self = this;
  1725. var newPosition = self._calculateCameraPosition({
  1726. lng: options.lng,
  1727. lat: options.lat,
  1728. alt: options.alt,
  1729. angle: self.angle,
  1730. });
  1731. alert(JSON.stringify(newPosition));
  1732. self.viewer.camera.setView({
  1733. destination: newPosition,
  1734. orientation: {
  1735. heading: Cesium.Math.toRadians(Cesium.Math.toDegrees(self.viewer.camera
  1736. .heading) + self.angle),
  1737. pitch: self.viewer.camera.pitch,
  1738. }
  1739. });
  1740. },
  1741. /**
  1742. * 设置显示范围
  1743. * @param {JSON} options 配置项
  1744. * lng{double}:经度
  1745. * lat{double}:纬度
  1746. * alt{double}:高度
  1747. * heading{double}:指北角度 度
  1748. * pitch{double}:垂直视角 度
  1749. * roll{double}:翻滚视角 度
  1750. */
  1751. setMapRange: function(options) {
  1752. this.viewer.camera.setView({
  1753. destination: Cesium.Cartesian3.fromDegrees(options.lng, options.lat, options.alt),
  1754. orientation: {
  1755. //此视角为观察者/相机
  1756. heading: options.heading,
  1757. pitch: Cesium.Math.toRadians(options.pitch),
  1758. roll: options.roll
  1759. }
  1760. });
  1761. },
  1762. /**
  1763. * 异步飞行
  1764. * @param {JSON} options 配置项
  1765. * target{Object}:飞行目的地目标
  1766. * duration{int}:飞行持续时间 秒
  1767. * radians{double}:旋转角度 度
  1768. * isRemove{boolean}:执行完成后是否删除目标 true/false
  1769. */
  1770. asyncFlyTo: function(options) {
  1771. var self = this;
  1772. return new Promise((resolve, reject) => {
  1773. /* 飞行 */
  1774. var flyPromise = self.viewer.flyTo(options.target, {
  1775. duration: options.duration, //飞行持续时间
  1776. offset: new Cesium.HeadingPitchRange(0.0, Cesium.Math.toRadians(options
  1777. .radians)),
  1778. });
  1779. /* 飞行完成 */
  1780. flyPromise.then(function(isFly) {
  1781. if (isFly && options.isRemove && options.target != undefined) {
  1782. self.viewer.entities.remove(options.target);
  1783. }
  1784. resolve(true);
  1785. })
  1786. });
  1787. },
  1788. /**
  1789. * 飞向矩形区域
  1790. * @param {JSON} options 配置项
  1791. * strLng{double}:矩形起始点经度
  1792. * strLat{double}:矩形起始点纬度
  1793. * endLng{double}:矩形终止点经度
  1794. * endLat{double}:矩形终止点纬度
  1795. */
  1796. flyToRectangle: function(options) {
  1797. var self = this;
  1798. this.entities.removeById('flyRectangle');
  1799. var extent = Cesium.Rectangle.fromDegrees(options.strLng, options.strLat, options.endLng,
  1800. options
  1801. .endLat);
  1802. /* 创建飞行矩形 */
  1803. var flyRectangle = this.entities.add({
  1804. id: 'flyRectangle',
  1805. name: 'flyRectangle',
  1806. rectangle: {
  1807. coordinates: extent,
  1808. material: Cesium.Color.GREEN.withAlpha(0),
  1809. height: 10.0,
  1810. outline: false
  1811. }
  1812. });
  1813. this.asyncFlyTo({
  1814. target: flyRectangle, //定位对象
  1815. isRemove: false, //定位完成后是否删除
  1816. duration: 3,
  1817. radians: -90,
  1818. }).then(function(isFly) {
  1819. if (isFly) {
  1820. self.asyncFlyTo({
  1821. target: flyRectangle, //定位对象
  1822. isRemove: true, //定位完成后是否删除
  1823. duration: 1,
  1824. radians: -40,
  1825. }).then(function(isFly) {
  1826. if (isFly && options.success != undefined) {
  1827. options.success();
  1828. }
  1829. })
  1830. }
  1831. }).catch(function(err) {
  1832. alert(err);
  1833. })
  1834. }
  1835. });
  1836. /**
  1837. * 特效相关 雨雪雾
  1838. */
  1839. CrMap.prototype.extend({
  1840. /**
  1841. * 开启下雪
  1842. */
  1843. _openSnow: function() {
  1844. return "uniform sampler2D colorTexture;\n\
  1845. varying vec2 v_textureCoordinates;\n\
  1846. \n\
  1847. float snow(vec2 uv,float scale)\n\
  1848. {\n\
  1849. float time = czm_frameNumber / 60.0;\n\
  1850. float w=smoothstep(1.,0.,-uv.y*(scale/10.));if(w<.1)return 0.;\n\
  1851. uv+=time/scale;uv.y+=time*2./scale;uv.x+=sin(uv.y+time*.5)/scale;\n\
  1852. uv*=scale;vec2 s=floor(uv),f=fract(uv),p;float k=3.,d;\n\
  1853. p=.5+.35*sin(11.*fract(sin((s+p+scale)*mat2(7,3,6,5))*5.))-f;d=length(p);k=min(d,k);\n\
  1854. k=smoothstep(0.,k,sin(f.x+f.y)*0.01);\n\
  1855. return k*w;\n\
  1856. }\n\
  1857. \n\
  1858. void main(void){\n\
  1859. vec2 resolution = czm_viewport.zw;\n\
  1860. vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);\n\
  1861. vec3 finalColor=vec3(0);\n\
  1862. float c = 0.0;\n\
  1863. c+=snow(uv,30.)*.0;\n\
  1864. c+=snow(uv,20.)*.0;\n\
  1865. c+=snow(uv,15.)*.0;\n\
  1866. c+=snow(uv,10.);\n\
  1867. c+=snow(uv,8.);\n\
  1868. c+=snow(uv,6.);\n\
  1869. c+=snow(uv,5.);\n\
  1870. finalColor=(vec3(c)); \n\
  1871. gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(finalColor,1), 0.5); \n\
  1872. \n\
  1873. }\n\
  1874. ";
  1875. },
  1876. /**
  1877. * 开启下雨
  1878. */
  1879. _openRain: function() {
  1880. return "uniform sampler2D colorTexture;\n\
  1881. varying vec2 v_textureCoordinates;\n\
  1882. \n\
  1883. float hash(float x){\n\
  1884. return fract(sin(x*133.3)*13.13);\n\
  1885. }\n\
  1886. \n\
  1887. void main(void){\n\
  1888. \n\
  1889. float time = czm_frameNumber / 60.0;\n\
  1890. vec2 resolution = czm_viewport.zw;\n\
  1891. \n\
  1892. vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);\n\
  1893. vec3 c=vec3(.6,.7,.8);\n\
  1894. \n\
  1895. float a=-.4;\n\
  1896. float si=sin(a),co=cos(a);\n\
  1897. uv*=mat2(co,-si,si,co);\n\
  1898. uv*=length(uv+vec2(0,4.9))*.3+1.;\n\
  1899. \n\
  1900. float v=1.-sin(hash(floor(uv.x*100.))*2.);\n\
  1901. float b=clamp(abs(sin(20.*time*v+uv.y*(5./(2.+v))))-.95,0.,1.)*20.;\n\
  1902. c*=v*b; \n\
  1903. \n\
  1904. gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(c,1), 0.5); \n\
  1905. }\n\
  1906. ";
  1907. },
  1908. /**
  1909. * 打开雾
  1910. */
  1911. _openFog: function() {
  1912. return 'uniform sampler2D colorTexture;\n' +
  1913. ' uniform sampler2D depthTexture;\n' +
  1914. ' varying vec2 v_textureCoordinates;\n' +
  1915. ' void main(void)\n' +
  1916. ' {\n' +
  1917. ' vec4 origcolor=texture2D(colorTexture, v_textureCoordinates);\n' +
  1918. ' vec4 fogcolor=vec4(0.8,0.8,0.8,0.5);\n' +
  1919. ' float depth = czm_readDepth(depthTexture, v_textureCoordinates);\n' +
  1920. ' vec4 depthcolor=texture2D(depthTexture, v_textureCoordinates);\n' +
  1921. ' float f=(depthcolor.r-0.55)/0.5;\n' +
  1922. ' if(f<0.0) f=0.0;\n' +
  1923. ' else if(f>1.0) f=1.0;\n' +
  1924. ' gl_FragColor = mix(origcolor,fogcolor,f);\n' +
  1925. ' }';
  1926. },
  1927. /**
  1928. * 开启雪模式
  1929. */
  1930. openSnow: function() {
  1931. var self = this;
  1932. var collection = self.viewer.scene.postProcessStages;
  1933. var fs_snow = self._openSnow();
  1934. self.snowStage = new Cesium.PostProcessStage({
  1935. name: 'czm_snow',
  1936. fragmentShader: fs_snow
  1937. });
  1938. collection.add(self.snowStage);
  1939. self.viewer.scene.requestRenderMode = false; //关闭主动渲染 否则无法下雪持续
  1940. self.viewer.scene.skyAtmosphere.hueShift = -0.8;
  1941. self.viewer.scene.skyAtmosphere.saturationShift = -0.7;
  1942. self.viewer.scene.skyAtmosphere.brightnessShift = -0.33;
  1943. self.viewer.scene.fog.density = 0.001;
  1944. self.viewer.scene.fog.minimumBrightness = 0.8;
  1945. },
  1946. /**
  1947. * 开启雨的模式
  1948. */
  1949. openRain: function() {
  1950. var self = this;
  1951. var collection = self.viewer.scene.postProcessStages;
  1952. var fs_snow = self._openRain();
  1953. self.rainStage = new Cesium.PostProcessStage({
  1954. name: 'czm_rain',
  1955. fragmentShader: fs_snow
  1956. });
  1957. collection.add(self.rainStage);
  1958. self.viewer.scene.requestRenderMode = false; //关闭主动渲染 否则无法下雪持续
  1959. self.viewer.scene.skyAtmosphere.hueShift = -0.8;
  1960. self.viewer.scene.skyAtmosphere.saturationShift = -0.7;
  1961. self.viewer.scene.skyAtmosphere.brightnessShift = -0.33;
  1962. self.viewer.scene.fog.density = 0.001;
  1963. self.viewer.scene.fog.minimumBrightness = 0.8;
  1964. },
  1965. /**
  1966. * 开启雾模式
  1967. */
  1968. openFog: function() {
  1969. var self = this;
  1970. var collection = self.viewer.scene.postProcessStages;
  1971. var fs_snow = self._openFog();
  1972. self.fogStage = new Cesium.PostProcessStage({
  1973. name: 'czm_fog',
  1974. fragmentShader: fs_snow
  1975. });
  1976. collection.add(self.fogStage);
  1977. self.viewer.scene.requestRenderMode = false; //关闭主动渲染 否则无法下雪持续
  1978. self.viewer.scene.skyAtmosphere.hueShift = -0.8;
  1979. self.viewer.scene.skyAtmosphere.saturationShift = -0.7;
  1980. self.viewer.scene.skyAtmosphere.brightnessShift = -0.33;
  1981. self.viewer.scene.fog.density = 0.001;
  1982. self.viewer.scene.fog.minimumBrightness = 0.8;
  1983. },
  1984. /**
  1985. * 关闭雨
  1986. */
  1987. closeRain: function() {
  1988. var self = this;
  1989. if (this.rainStage) {
  1990. this.viewer.scene.postProcessStages.remove(this.rainStage);
  1991. this.rainStage = undefined;
  1992. // setTimeout(function(){
  1993. // self.viewer.scene.requestRenderMode = true; //启动主动渲染 否则无法下雪持续
  1994. // },1000);
  1995. }
  1996. },
  1997. /**
  1998. * 关闭雪
  1999. */
  2000. closeSnow: function() {
  2001. var self = this;
  2002. if (this.snowStage) {
  2003. this.viewer.scene.postProcessStages.remove(this.snowStage);
  2004. this.snowStage = undefined;
  2005. // setTimeout(function(){
  2006. // self.viewer.scene.requestRenderMode = true; //启动主动渲染 否则无法下雪持续
  2007. // },1000);
  2008. }
  2009. },
  2010. /**
  2011. * 关闭雾
  2012. */
  2013. closeFog: function() {
  2014. var self = this;
  2015. if (this.fogStage) {
  2016. this.viewer.scene.postProcessStages.remove(this.fogStage);
  2017. this.fogStage = undefined;
  2018. // setTimeout(function(){
  2019. // self.viewer.scene.requestRenderMode = true; //启动主动渲染 否则无法下雪持续
  2020. // },1000);
  2021. }
  2022. },
  2023. });
  2024. /**
  2025. * 调起查询工具
  2026. */
  2027. CrMap.prototype.extend({
  2028. /**
  2029. * 点查询
  2030. */
  2031. queryPoint: function() {
  2032. this.actionType = ActionType.queryAttribute;
  2033. },
  2034. });
  2035. /**
  2036. * 矢量服务查询
  2037. */
  2038. CrMap.prototype.extend({
  2039. /**
  2040. * 获取tile分级
  2041. * @param {Object} height 高度
  2042. */
  2043. _getLevel: function(height) {
  2044. if (height > 48000000) {
  2045. return 0;
  2046. } else if (height > 24000000) {
  2047. return 1;
  2048. } else if (height > 12000000) {
  2049. return 2;
  2050. } else if (height > 6000000) {
  2051. return 3;
  2052. } else if (height > 3000000) {
  2053. return 4;
  2054. } else if (height > 1500000) {
  2055. return 5;
  2056. } else if (height > 750000) {
  2057. return 6;
  2058. } else if (height > 375000) {
  2059. return 7;
  2060. } else if (height > 187500) {
  2061. return 8;
  2062. } else if (height > 93750) {
  2063. return 9;
  2064. } else if (height > 46875) {
  2065. return 10;
  2066. } else if (height > 23437.5) {
  2067. return 11;
  2068. } else if (height > 11718.75) {
  2069. return 12;
  2070. } else if (height > 5859.38) {
  2071. return 13;
  2072. } else if (height > 2929.69) {
  2073. return 14;
  2074. } else if (height > 1464.84) {
  2075. return 15;
  2076. } else if (height > 732.42) {
  2077. return 16;
  2078. } else if (height > 366.21) {
  2079. return 17;
  2080. } else {
  2081. return 18;
  2082. }
  2083. },
  2084. /**
  2085. * 点击查询矢量数据
  2086. * @param {Object} position 鼠标点击位置
  2087. */
  2088. _queryVectorLayer(position) {
  2089. var self = this;
  2090. //测试 打印查询的图层看看
  2091. // for(var i=0;i<self.queryLayers.length;i++){
  2092. // var queryLayer = self.queryLayers[i];
  2093. // console.log("i = " + i + " LayerId = " + queryLayer.id);
  2094. // }
  2095. //查询射线
  2096. var ray = self.viewer.camera.getPickRay(position);
  2097. //查询射线坐标位置
  2098. var cartesian = self.viewer.scene.globe.pick(ray, self.viewer.scene);
  2099. if (cartesian) {
  2100. var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
  2101. if (cartographic) {
  2102. var alti = self.viewer.camera.positionCartographic.height;
  2103. var level = self._getLevel(alti);
  2104. //通过callback方式进行 否则无法一次性返回
  2105. self.attributesQueryIndex = 0; //初始化查询索引
  2106. self.attributesData = []; //重置数组
  2107. self._queryAttribuesCallback(cartographic, level); //执行回调查询
  2108. }
  2109. }
  2110. },
  2111. /**
  2112. * 属性查询循环回调
  2113. * @param {Object} cartographic 图形点
  2114. * @param {Object} level 等级
  2115. */
  2116. _queryAttribuesCallback: function(cartographic, level) {
  2117. var self = this;
  2118. if (self.attributesQueryIndex > self.queryLayers.length - 1) {
  2119. //如果事件存在 则回调
  2120. if (self.onQueryVectorResult != undefined) {
  2121. //在挂接以下Entity的查询信息
  2122. for (var i = 0; i < self.attributesEntity.length; i++) {
  2123. self.attributesData.push(self.attributesEntity[i]);
  2124. }
  2125. self.onQueryVectorResult(self.attributesData);
  2126. }
  2127. } else {
  2128. var queryConfig = self.queryLayers[self.attributesQueryIndex];
  2129. var imageryProvider = queryConfig.provider;
  2130. if (imageryProvider.ready) {
  2131. var xy = new Cesium.Cartesian2();
  2132. xy = imageryProvider.tilingScheme.positionToTileXY(cartographic, level, xy);
  2133. var promise = imageryProvider.pickFeatures(xy.x, xy.y, level, cartographic.longitude,
  2134. cartographic.latitude);
  2135. Cesium.when(promise, function(resData) {
  2136. if (window[queryConfig.id] != undefined && window[queryConfig.id].show) {
  2137. for (var i = 0; i < resData.length; i++) {
  2138. /* 此处需要判断一下 点击的是点、线、面 */
  2139. var geoType = resData[i].data.geometryType;
  2140. console.log(geoType);
  2141. var geometry = {
  2142. type: 'non',
  2143. pts: [],
  2144. }
  2145. if (geoType === "esriGeometryPoint") {
  2146. geometry.type = 'point';
  2147. geometry.pts.push({
  2148. lng: resData[i].data.geometry.x,
  2149. lat: resData[i].data.geometry.y,
  2150. })
  2151. } else if (geoType === "esriGeometryPolygon") {
  2152. geometry.type = 'polygon';
  2153. var rings = resData[i].data.geometry.rings;
  2154. for (var rIdx = 0; rIdx < rings.length; rIdx++) {
  2155. var subRing = resData[i].data.geometry.rings[rIdx];
  2156. var pts = [];
  2157. for (var ptIdx = 0; ptIdx < subRing.length; ptIdx++) {
  2158. pts.push({
  2159. lng: subRing[ptIdx][0],
  2160. lat: subRing[ptIdx][1],
  2161. })
  2162. };
  2163. geometry.pts.push(pts);
  2164. }
  2165. }
  2166. self.attributesData.push({
  2167. layerName: resData[i].data.layerName,
  2168. attributes: resData[i].data.attributes,
  2169. geometry: geometry,
  2170. });
  2171. }
  2172. }
  2173. self.attributesQueryIndex++;
  2174. self._queryAttribuesCallback(cartographic, level);
  2175. });
  2176. }
  2177. }
  2178. },
  2179. });
  2180. /**
  2181. * 绘制相关
  2182. */
  2183. CrMap.prototype.extend({
  2184. /**
  2185. * 根据名称删除绘制的实体
  2186. * @param {Object} name 实体名称
  2187. */
  2188. _removeEntities: function(name) {
  2189. var entities = this.viewer.entities;
  2190. var delEntitys = [];
  2191. //循环查找符合条件的Entity
  2192. for (var i = 0; i < entities.values.length; i++) {
  2193. if (entities.values[i].name == name) {
  2194. delEntitys.push(entities.values[i]);
  2195. }
  2196. }
  2197. //删除符合条件的Entity
  2198. for (var i = 0; i < delEntitys.length; i++) {
  2199. entities.remove(delEntitys[i]);
  2200. }
  2201. this.viewer.scene.requestRenderMode = true; //停止主动刷新
  2202. this.updateSence(); //主动刷新以下
  2203. },
  2204. /**
  2205. * @param {JSON} option
  2206. * {name: points:[{lng,lat},...] color:{r: g: b: a:}}
  2207. */
  2208. addSelectPolylineEntity: function(options) {
  2209. var self = this;
  2210. //解析线坐标
  2211. var linepts = [];
  2212. for (var i = 0; i < options.points.length; i++) {
  2213. linepts.push(Cesium.Cartesian3.fromDegrees(options.points[i].lng, options.points[i].lat));
  2214. }
  2215. var x = 1.0;
  2216. var flog = true;
  2217. var plineEntity = new Cesium.Entity({
  2218. name: options.name,
  2219. polyline: {
  2220. show: true,
  2221. positions: linepts,
  2222. width: 6,
  2223. clampToGround: true,
  2224. material: new Cesium.PolylineGlowMaterialProperty({
  2225. glowPower: 0.2, //一个数字属性,指定发光强度,占总线宽的百分���。
  2226. color: Cesium.Color.BLUE,
  2227. }),
  2228. //distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 2000)
  2229. }
  2230. });
  2231. //加入图层
  2232. self.viewer.entities.add(plineEntity);
  2233. //更新场景
  2234. self.updateSence();
  2235. plineEntity.polyline.material = new Cesium.ColorMaterialProperty(new Cesium.CallbackProperty(
  2236. function() {
  2237. if (flog) {
  2238. x = x - 0.01;
  2239. if (x <= 0) {
  2240. flog = false;
  2241. }
  2242. } else {
  2243. x = x + 0.01;
  2244. if (x >= 1) {
  2245. flog = true;
  2246. }
  2247. }
  2248. self.updateSence();
  2249. // return {
  2250. // glowPower: 0.25,
  2251. // color: Cesium.Color.RED.withAlpha(0.3),
  2252. // };
  2253. return Cesium.Color.RED.withAlpha(x);
  2254. }, false));
  2255. },
  2256. /**
  2257. * @param {JSON} options
  2258. * {name: point:{lng,lat}}
  2259. */
  2260. addSelectPointEntity: function(options) {
  2261. var self = this;
  2262. var a = true;
  2263. var n = true;
  2264. var o = true;
  2265. var markerOpacity = 1;
  2266. var pixelSize = 3;
  2267. var outLineOpacity = 0.7;
  2268. var ptColor = Cesium.Color.RED;
  2269. var pixelMax = 50;
  2270. var pointEntity = {
  2271. name: options.name,
  2272. position: Cesium.Cartesian3.fromDegrees(options.point.lng, options.point.lat),
  2273. point: {
  2274. heightReference: 50,
  2275. color: new Cesium.CallbackProperty(() => {
  2276. self.updateSence();
  2277. return a ? (markerOpacity -= .03,
  2278. markerOpacity <= 0 && (a = false)) : (markerOpacity = 1,
  2279. a = true),
  2280. ptColor.withAlpha(markerOpacity)
  2281. }, false),
  2282. pixelSize: new Cesium.CallbackProperty((time, result) => {
  2283. self.updateSence();
  2284. return n ? (pixelSize += 1,
  2285. pixelSize >= pixelMax && (n = false)) : (pixelSize = 3,
  2286. n = true),
  2287. pixelSize
  2288. }, false),
  2289. // outlineColor: new Cesium.CallbackProperty(() => {
  2290. // self.updateSence();
  2291. // return o ? (outLineOpacity -= .035,
  2292. // outLineOpacity <= 0 && (o = false)) : (outLineOpacity = .7,
  2293. // o = true),
  2294. // ptColor.withAlpha(outLineOpacity)
  2295. // }, false),
  2296. // outlineWidth: 2,
  2297. scaleByDistance: new Cesium.NearFarScalar(1200, 1, 5200, 0.4),
  2298. }
  2299. };
  2300. //加入图层
  2301. self.entities.add(pointEntity);
  2302. //更新场景
  2303. self.updateSence();
  2304. },
  2305. /**
  2306. * 添加面对像
  2307. * @param {JSON} options
  2308. * id:添加的面对象Id
  2309. * config:(JSON){name:图层名称 geo:矢量数据}
  2310. * points:[{lng,lat},...]
  2311. * color:{r: g: b: a:}}
  2312. * description:(JSON)
  2313. */
  2314. addPolygonEntityTest: function(options) {
  2315. var self = this;
  2316. //解析线坐标
  2317. var points = [];
  2318. for (var i = 0; i < options.points.length; i++) {
  2319. points.push(Cesium.Cartesian3.fromDegrees(options.points[i].lng, options.points[i].lat));
  2320. }
  2321. var polygonEntity = new Cesium.Entity({
  2322. name: options.config.name,
  2323. id: options.id,
  2324. polygon: {
  2325. hierarchy: {
  2326. positions: points,
  2327. },
  2328. material: self._toColor(options.color.r, options.color.g, options.color.b,
  2329. options
  2330. .color.a),
  2331. classificationType: Cesium.ClassificationType.BOTH,
  2332. }
  2333. });
  2334. //加入图层
  2335. self.viewer.entities.add(polygonEntity);
  2336. },
  2337. /**
  2338. * 添加面对像
  2339. * @param {JSON} options
  2340. * id:添加的面对象Id
  2341. * config:(JSON){name:图层名称 geo:矢量数据}
  2342. * points:[{lng,lat},...]
  2343. * color:{r: g: b: a:}}
  2344. * description:(JSON)
  2345. */
  2346. addPolygonEntity: function(options) {
  2347. var self = this;
  2348. //解析线坐标
  2349. var points = [];
  2350. var pts = [];
  2351. for (var i = 0; i < options.points.length; i++) {
  2352. points.push(Cesium.Cartesian3.fromDegrees(options.points[i].lng, options.points[i].lat));
  2353. pts.push({
  2354. lng: options.points[i].lng,
  2355. lat: options.points[i].lat,
  2356. });
  2357. }
  2358. var polygonEntity = new Cesium.Entity({
  2359. name: JSON.stringify({
  2360. name: options.config.name,
  2361. geometry: {
  2362. type: 'polygon',
  2363. pts: [pts],
  2364. },
  2365. }),
  2366. id: options.id,
  2367. description: JSON.stringify(options.description),
  2368. polygon: {
  2369. hierarchy: {
  2370. positions: points,
  2371. },
  2372. material: self._toColor(options.color.r, options.color.g, options.color.b,
  2373. options
  2374. .color.a),
  2375. classificationType: Cesium.ClassificationType.BOTH,
  2376. }
  2377. });
  2378. //加入图层
  2379. self.viewer.entities.add(polygonEntity);
  2380. },
  2381. /**
  2382. * 添加点实体
  2383. * @param {JSON} options 数据项
  2384. * {name:实体名称 lng:经度 lat:纬度}
  2385. * point:{color:'0,0,0,1' outlineColor:'0,0,0,1' size: outlineWidth:}
  2386. * label:{text: size: family: color: offset:[,]}
  2387. * billboard:{img: scale:}
  2388. */
  2389. addPoint: function(options) {
  2390. var self = this;
  2391. var point = Cesium.Cartesian3.fromDegrees(options.lng, options.lat, 200);
  2392. var pointEntity = new Cesium.Entity({
  2393. name: options.name,
  2394. position: point,
  2395. });
  2396. var configPoint = options.point;
  2397. var configLabel = options.label;
  2398. var configBillboard = options.billboard;
  2399. /* 配置点信息 */
  2400. if (configPoint != undefined) {
  2401. pointEntity.point = {
  2402. color: Cesium.Color.fromCssColorString('rgba(' + configPoint.color + ')'),
  2403. pixelSize: configPoint.size,
  2404. outlineColor: Cesium.Color.fromCssColorString('rgba(' + configPoint.outlineColor +
  2405. ')'),
  2406. outlineWidth: configPoint.outlineWidth,
  2407. heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  2408. }
  2409. }
  2410. /* 配置广告牌信息 */
  2411. if (configBillboard != undefined) {
  2412. pointEntity.billboard = {
  2413. image: configBillboard.img,
  2414. scale: configBillboard.scale,
  2415. horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  2416. verticalOrigin: Cesium.VerticalOrigin.BASELINE,
  2417. heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  2418. };
  2419. }
  2420. /* 配置标签 */
  2421. if (configLabel != undefined) {
  2422. pointEntity.label = {
  2423. text: configLabel.text,
  2424. font: configLabel.size + 'px ' + configLabel.family,
  2425. scale: 0.5,
  2426. heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
  2427. fillColor: Cesium.Color.WHITE,
  2428. outlineColor: Cesium.Color.fromCssColorString('rgba(' + configLabel.color + ')'),
  2429. outlineWidth: 4,
  2430. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  2431. horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
  2432. verticalOrigin: Cesium.VerticalOrigin.center,
  2433. pixelOffset: new Cesium.Cartesian2(configLabel.offset[0], configLabel.offset[1]),
  2434. showBackground: false,
  2435. }
  2436. }
  2437. /* 添加实体 */
  2438. self.entities.add(pointEntity);
  2439. /* 更新场景 */
  2440. self.updateSence();
  2441. },
  2442. /**
  2443. * 获取旋转值
  2444. */
  2445. _getRotationValue: function() {
  2446. var self = this;
  2447. return function() {
  2448. self.areaRotation += 0.005;
  2449. return self.areaRotation;
  2450. }
  2451. },
  2452. /**
  2453. * 添加旋转区域
  2454. * @param {JSON} options 配置项
  2455. * strLng{double}:矩形起始点经度
  2456. * strLat{double}:矩形起始点纬度
  2457. * endLng{double}:矩形终止点经度
  2458. * endLag{double}:矩形终止点纬度
  2459. * northImage{String}:指北照片Url
  2460. * scaleImage{String}:旋转照片Url
  2461. */
  2462. addRotateArea: function(options) {
  2463. var self = this;
  2464. // alert(self.serverUrl + options.northImage);
  2465. self.entities.add({
  2466. name: "rotateArea",
  2467. rectangle: {
  2468. coordinates: Cesium.Rectangle.fromDegrees(options.strLng, options.strLat,
  2469. options
  2470. .endLng, options.endLat),
  2471. material: self.serverUrl + options.northImage,
  2472. classificationType: Cesium.ClassificationType.TERRAIN,
  2473. },
  2474. });
  2475. // self.entities.add({
  2476. // name: "rotateArea",
  2477. // rectangle: {
  2478. // coordinates: Cesium.Rectangle.fromDegrees(options.strLng, options.strLat, options
  2479. // .endLng, options.endLat),
  2480. // material: self.serverUrl + options.scaleImage,
  2481. // rotation: new Cesium.CallbackProperty(self._getRotationValue(), false),
  2482. // stRotation: new Cesium.CallbackProperty(self._getRotationValue(), false),
  2483. // classificationType: Cesium.ClassificationType.TERRAIN,
  2484. // },
  2485. // });
  2486. },
  2487. /**
  2488. * 从集合中删除具有提供的ID的实体
  2489. * 如果已删除项目,则为true;如果集合中不存在具有提供的ID的项目,则为false
  2490. * @param {Object} entityId 实体Id
  2491. */
  2492. removeEntityById: function(entityId) {
  2493. var isDel = this.viewer.entities.removeById(entityId);
  2494. this.updateSence();
  2495. return isDel;
  2496. },
  2497. /**
  2498. * 根据名称删除实体
  2499. * @param {Object} entityName 实体名称
  2500. */
  2501. removeEntityByName: function(entityName) {
  2502. this._removeEntities(entityName);
  2503. },
  2504. });
  2505. /**
  2506. * OD线相关
  2507. */
  2508. CrMap.prototype.extend({
  2509. /**
  2510. * 计算间隔点
  2511. * @param {JSON} options
  2512. * @param {Array} resultOut
  2513. */
  2514. _parabolaEquation: function(options, resultOut) {
  2515. //方程 y=-(4h/L^2)*x^2+h h:顶点高度 L:横纵间距较大者
  2516. var h = options.height && options.height < 5000 ? options.height : 5000;
  2517. var L = Math.abs(options.pt1.lon - options.pt2.lon) > Math.abs(options.pt1.lat - options.pt2
  2518. .lat) ?
  2519. Math.abs(options.pt1.lon - options.pt2.lon) : Math.abs(options.pt1.lat - options.pt2.lat);
  2520. var num = options.num && options.num > 50 ? options.num : 50;
  2521. var result = [];
  2522. var tempResult = []; //临时数组
  2523. var dlt = L / num;
  2524. var addHeight = options.pt1.alt > options.pt2.alt ? options.pt1.alt : options.pt2.alt;
  2525. var maxHeight = addHeight + h;
  2526. var minHeight1 = options.pt1.alt;
  2527. var minHeight2 = options.pt2.alt;
  2528. if (Math.abs(options.pt1.lon - options.pt2.lon) > Math.abs(options.pt1.lat - options.pt2
  2529. .lat)) { //以lon为基准
  2530. var delLat = (options.pt2.lat - options.pt1.lat) / num;
  2531. if (options.pt1.lon - options.pt2.lon > 0) {
  2532. dlt = -dlt;
  2533. }
  2534. for (var i = 1; i < num; i++) {
  2535. var tempH = h - Math.pow((-0.5 * L + Math.abs(dlt) * i), 2) * 4 * h / Math.pow(L, 2);
  2536. var lon = options.pt1.lon + dlt * i;
  2537. var lat = options.pt1.lat + delLat * i;
  2538. var alt = undefined;
  2539. if (Math.abs(dlt) * i == 0.5 * L) {
  2540. alt = maxHeight;
  2541. } else if (Math.abs(dlt) * i < 0.5 * L) {
  2542. //说明是抛物线左侧
  2543. alt = ((maxHeight - minHeight1) / h) * tempH + minHeight1;
  2544. } else {
  2545. //说明是抛物线右侧
  2546. alt = ((maxHeight - minHeight2) / h) * tempH + minHeight2;
  2547. }
  2548. tempResult.push([lon, lat, alt]);
  2549. }
  2550. } else { //以lat为基准
  2551. var delLon = (options.pt2.lon - options.pt1.lon) / num;
  2552. if (options.pt1.lat - options.pt2.lat > 0) {
  2553. dlt = -dlt;
  2554. }
  2555. for (var i = 1; i < num; i++) {
  2556. var tempH = h - Math.pow((-0.5 * L + Math.abs(dlt) * i), 2) * 4 * h / Math.pow(L, 2);
  2557. var lon = options.pt1.lon + delLon * i;
  2558. var lat = options.pt1.lat + dlt * i;
  2559. var alt = undefined;
  2560. if (Math.abs(dlt) * i == 0.5 * L) {
  2561. alt = maxHeight;
  2562. } else if (Math.abs(dlt) * i < 0.5 * L) {
  2563. //说明是抛物线左侧
  2564. alt = ((maxHeight - minHeight1) / h) * tempH + minHeight1;
  2565. } else {
  2566. //说明是抛物线右侧
  2567. alt = ((maxHeight - minHeight2) / h) * tempH + minHeight2;
  2568. }
  2569. tempResult.push([lon, lat, alt]);
  2570. }
  2571. }
  2572. /* 对结果进行处理 */
  2573. result.push([options.pt1.lon, options.pt1.lat, options.pt1.alt]);
  2574. for (var i = 0; i < tempResult.length; i++) {
  2575. result.push(tempResult[i]);
  2576. }
  2577. result.push([options.pt2.lon, options.pt2.lat, options.pt2.alt]);
  2578. if (resultOut != undefined) {
  2579. resultOut = result;
  2580. }
  2581. return result;
  2582. },
  2583. /**
  2584. * 设置OD线
  2585. * @param {JSON} center 中心点
  2586. * @param {Array(JSON)} cities 到达点
  2587. * @param {String} name 添加的OD线的名称
  2588. */
  2589. addODLine: function(center, cities, name) {
  2590. var self = this; //Cesium.Color.BLUE
  2591. var material = new Cesium.PolylineTrailLinkMaterialProperty(self._toColor(0, 0, 255, 1.0),
  2592. 4000);
  2593. /* 添加OD线 */
  2594. for (var j = 0; j < cities.length; j++) {
  2595. var points = self._parabolaEquation({
  2596. pt1: center,
  2597. pt2: cities[j],
  2598. height: 800,
  2599. num: 10
  2600. });
  2601. var pointArr = [];
  2602. for (var i = 0; i < points.length; i++) {
  2603. pointArr.push(points[i][0], points[i][1], points[i][2]);
  2604. }
  2605. self.entities.add({
  2606. name: name,
  2607. polyline: {
  2608. positions: Cesium.Cartesian3.fromDegreesArrayHeights(pointArr),
  2609. width: 2,
  2610. material: material
  2611. }
  2612. });
  2613. }
  2614. /* 添加目标点 */
  2615. self.entities.add({
  2616. name: name,
  2617. position: Cesium.Cartesian3.fromDegrees(center.lon, center.lat, center.alt),
  2618. point: {
  2619. pixelSize: 6,
  2620. color: Cesium.Color.BLUE
  2621. }
  2622. });
  2623. /* 添加来源点数组 */
  2624. for (var i = 0; i < cities.length; i++) {
  2625. self.entities.add({
  2626. name: name,
  2627. position: Cesium.Cartesian3.fromDegrees(cities[i].lon, cities[i].lat, cities[i]
  2628. .alt),
  2629. point: {
  2630. pixelSize: 6,
  2631. color: Cesium.Color.RED
  2632. }
  2633. });
  2634. }
  2635. self.viewer.scene.requestRenderMode = false; //开启主动刷新
  2636. },
  2637. /**
  2638. * 移除OD线
  2639. * @param {Object} name OD线的名称
  2640. */
  2641. removeODLine: function(name) {
  2642. this._removeEntities(name);
  2643. }
  2644. });
  2645. /**
  2646. * 地图案件查询相关
  2647. */
  2648. CrMap.prototype.extend({
  2649. /**
  2650. * 案件查询 点方式查询 点击事件
  2651. * @param {Object} event 点击事件
  2652. */
  2653. _eventCasePointQueryMouseClick: function(event) {
  2654. var self = this;
  2655. var ray = this.viewer.camera.getPickRay(event.position);
  2656. var cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
  2657. this.measurePoints.push(cartesian);
  2658. //添加点和标注
  2659. this.entities.add({
  2660. name: 'measure',
  2661. position: self.measurePoints[self.measurePoints.length - 1],
  2662. point: {
  2663. pixelSize: self.measurePointStyle.pixelSize,
  2664. color: self.measurePointStyle.color,
  2665. outlineColor: self.measurePointStyle.outlineColor,
  2666. outlineWidth: self.measurePointStyle.outlineWidth,
  2667. },
  2668. });
  2669. //还原工具 以免多次点击
  2670. this.actionType = ActionType.non;
  2671. //刷新场景
  2672. this.updateSence(); //主动刷新场景
  2673. //弹出气泡查询窗口
  2674. var g84Coord = this._wordToWGS84(cartesian); //世界坐标转经纬度坐标
  2675. if (this.onPopoverQueryTool != undefined) {
  2676. this.onPopoverQueryTool({
  2677. x: event.position.x,
  2678. y: event.position.y,
  2679. lng: g84Coord.lng,
  2680. lat: g84Coord.lat,
  2681. alt: g84Coord.alt,
  2682. extent: g84Coord.lng + "," + g84Coord.lat,
  2683. queryType: 'point',
  2684. });
  2685. }
  2686. },
  2687. /**
  2688. * 案件查询 区域方式查询 点击事件
  2689. * @param {Object} event 点击事件
  2690. */
  2691. _eventCasePolygonQueryMouseClick: function(event) {
  2692. var self = this;
  2693. var ray = this.viewer.camera.getPickRay(event.position);
  2694. var cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
  2695. this.measurePoints.push(cartesian);
  2696. //添加绘制面
  2697. if (this.measurePoints.length > 2 && !Cesium.defined(self.measurePolygon)) {
  2698. /* 添加一个面 */
  2699. self.measurePolygon = new Cesium.Entity({
  2700. name: 'measure',
  2701. polygon: {
  2702. show: true,
  2703. hierarchy: new Cesium.CallbackProperty(self._measureUpdatePolygon(),
  2704. false),
  2705. material: Cesium.Color.GREEN.withAlpha(0.3),
  2706. }
  2707. })
  2708. self.entities.add(self.measurePolygon);
  2709. }
  2710. //添加点
  2711. this.entities.add({
  2712. name: 'measure',
  2713. position: self.measurePoints[self.measurePoints.length - 1],
  2714. point: {
  2715. pixelSize: self.measurePointStyle.pixelSize,
  2716. color: self.measurePointStyle.color,
  2717. outlineColor: self.measurePointStyle.outlineColor,
  2718. outlineWidth: self.measurePointStyle.outlineWidth,
  2719. },
  2720. });
  2721. //判断是否显示查询按钮气泡窗口
  2722. if (self.measurePoints.length >= 4) {
  2723. /* 转换全部坐标点 */
  2724. var queryExtent = undefined;
  2725. for (var i = 0; i < self.measurePoints.length; i++) {
  2726. var g84 = this._wordToWGS84(self.measurePoints[i]); //世界坐标转经纬度坐标
  2727. if (queryExtent == undefined) queryExtent = g84.lng + "," + g84.lat;
  2728. else queryExtent += "," + g84.lng + "," + g84.lat;
  2729. }
  2730. var g84Coord = this._wordToWGS84(cartesian); //世界坐标转经纬度坐标
  2731. if (this.onPopoverQueryTool != undefined) {
  2732. this.onPopoverQueryTool({
  2733. x: event.position.x,
  2734. y: event.position.y,
  2735. lng: g84Coord.lng,
  2736. lat: g84Coord.lat,
  2737. alt: g84Coord.alt,
  2738. extent: queryExtent,
  2739. queryType: 'polygon',
  2740. });
  2741. }
  2742. }
  2743. this.updateSence(); //主动刷新场景
  2744. },
  2745. /**
  2746. * 地图上案件点查询
  2747. * @param {function} callback 查询提示信息回调
  2748. */
  2749. casePointQuery: function(callback) {
  2750. this._measureInit();
  2751. this.actionType = ActionType.casePointQuery;
  2752. if (callback != undefined) {
  2753. callback("单击案件位置查询!");
  2754. }
  2755. },
  2756. /**
  2757. * 地图上案件区域查询
  2758. * @param {Object} callback 查询提示信息回调
  2759. */
  2760. casePolygonQuery: function(callback) {
  2761. this._measureInit();
  2762. this.actionType = ActionType.casePolygonQuery;
  2763. if (callback != undefined) {
  2764. callback("单击绘制查询区域,点击开始查询按钮进行查询!");
  2765. }
  2766. }
  2767. });
  2768. /**
  2769. * 测量相关
  2770. */
  2771. CrMap.prototype.extend({
  2772. /**
  2773. * 添加广告牌和标签
  2774. * @param {JSON} options
  2775. * position{Cartesian3}:位置
  2776. * text{string}:标签
  2777. */
  2778. _measureAddBillboardAndLabel: function(options) {
  2779. var self = this;
  2780. var entity = new Cesium.Entity({
  2781. name: 'measure',
  2782. position: options.position,
  2783. billboard: {
  2784. image: self.serverUrl + 'ico_measure_location.png',
  2785. horizontalOrigin: Cesium.HorizontalOrigin.center,
  2786. verticalOrigin: Cesium.VerticalOrigin.bottom,
  2787. scale: 0.5,
  2788. pixelOffset: new Cesium.Cartesian2(0, -10),
  2789. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  2790. }
  2791. });
  2792. /* 判断是否添加标注 */
  2793. if (options.text != undefined) {
  2794. entity.label = {
  2795. text: options.text,
  2796. font: '12px sans-serif',
  2797. fillColor: this._toColor(255, 255, 255, 1.0),
  2798. outlineColor: this._toColor(0, 154, 94, 1.0),
  2799. style: Cesium.LabelStyle.FILL_AND_OUTLINE,
  2800. outlineWidth: 1.0,
  2801. verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
  2802. pixelOffset: new Cesium.Cartesian2(0, -28),
  2803. showBackground: true,
  2804. backgroundColor: this._toColor(0, 0, 0, 0.6),
  2805. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  2806. }
  2807. }
  2808. this.entities.add(entity);
  2809. },
  2810. /**
  2811. * 添加测量多段线
  2812. */
  2813. _measureAddPolyline: function() {
  2814. if (!Cesium.defined(this.measurePolyline)) {
  2815. this.measurePolyline = new Cesium.Entity({
  2816. name: 'measure',
  2817. polyline: {
  2818. show: true,
  2819. positions: new Cesium.CallbackProperty(this._measureUpdatePolyline(),
  2820. false),
  2821. material: this._toColor(0, 255, 0, 0.6),
  2822. width: 2,
  2823. clampToGround: true, //开启贴地 如果有模型则贴模型
  2824. }
  2825. })
  2826. this.entities.add(this.measurePolyline);
  2827. }
  2828. },
  2829. /**
  2830. * 添加一个测量面
  2831. */
  2832. _measureAddPolygon: function() {
  2833. if (!Cesium.defined(this.measurePolygon)) {
  2834. this.measurePolygon = new Cesium.Entity({
  2835. name: 'measure',
  2836. polygon: {
  2837. show: true,
  2838. hierarchy: new Cesium.CallbackProperty(this._measureUpdatePolygon(),
  2839. false),
  2840. material: Cesium.Color.GREEN.withAlpha(0.3),
  2841. classificationType: Cesium.ClassificationType.BOTH,
  2842. }
  2843. })
  2844. this.entities.add(this.measurePolygon);
  2845. }
  2846. },
  2847. /**
  2848. * 测量长度的鼠标点击事件
  2849. * @param {Object} event 事件
  2850. */
  2851. _eventMeasureLengthMouseClick: function(event) {
  2852. var self = this;
  2853. /* 根据屏幕位置获取经度、纬度和高度信息 */
  2854. var resLocation = this._getLocation(event.position);
  2855. /* 创建空间三维坐标 */
  2856. var cartesian = Cesium.Cartesian3.fromDegrees(resLocation.lng, resLocation.lat, resLocation.height);
  2857. /* 将创建的空间位置存储到点集合 */
  2858. this.measurePoints.push(cartesian.clone());
  2859. if (this.measurePoints.length > 1) {
  2860. this.measureLengthResult = this._measureSpaceDistance(this.measurePoints);
  2861. } else {
  2862. this.measureLengthResult = "起点";
  2863. }
  2864. /* 添加线 */
  2865. this._measureAddPolyline();
  2866. /* 添加广告牌定位标签和标注 */
  2867. this._measureAddBillboardAndLabel({
  2868. position: self.measurePoints[self.measurePoints.length - 1],
  2869. text: self.measureLengthResult,
  2870. });
  2871. this.updateSence(); //主动刷新场景
  2872. },
  2873. /**
  2874. * 测量面积的鼠标点击事件
  2875. * @param {Object} event 事件
  2876. */
  2877. _eventMeasureAreaMouseClick: function(event) {
  2878. var self = this;
  2879. /* 根据屏幕位置获取经度、纬度和高度信息 */
  2880. var resLocation = this._getLocation(event.position);
  2881. /* 创建空间三维坐标 */
  2882. var cartesian = Cesium.Cartesian3.fromDegrees(resLocation.lng, resLocation.lat, resLocation.height);
  2883. /* 将创建的空间位置存储到点集合 */
  2884. this.measurePoints.push(cartesian.clone());
  2885. /* 添加点到计算集合 */
  2886. this.measureTempPoints.push({
  2887. lon: resLocation.lng,
  2888. lat: resLocation.lat,
  2889. hei: resLocation.height
  2890. });
  2891. if (this.measurePoints.length > 2) {
  2892. this.measureAreaResult = this._measureArea(this.measureTempPoints); //计算面积
  2893. if (this.measurePoints.length == 3) {
  2894. this._measureAddPolygon(); //添加测量面
  2895. /* 添加广告牌定位标签和标注 */
  2896. this._measureAddBillboardAndLabel({
  2897. position: self.measurePoints[0],
  2898. text: new Cesium.CallbackProperty(self._measureUpdateLabelText(), false),
  2899. });
  2900. } else {
  2901. /* 添加广告牌定位标签 */
  2902. this._measureAddBillboardAndLabel({
  2903. position: self.measurePoints[self.measurePoints.length - 1],
  2904. });
  2905. }
  2906. } else {
  2907. /* 添加广告牌定位标签 */
  2908. this._measureAddBillboardAndLabel({
  2909. position: self.measurePoints[self.measurePoints.length - 1],
  2910. });
  2911. }
  2912. this.updateSence(); //主动刷新场景
  2913. },
  2914. /**
  2915. * 测量长度点集合属性回调
  2916. */
  2917. _measureUpdatePolyline: function() {
  2918. var self = this;
  2919. return function() {
  2920. return self.measurePoints;
  2921. };
  2922. },
  2923. /**
  2924. * 测量长度更新标签回调位置
  2925. */
  2926. _measureUpdateLabel: function() {
  2927. var self = this;
  2928. return function() {
  2929. return self.measurePoints[self.measurePoints.length - 1];
  2930. };
  2931. },
  2932. /**
  2933. * 测量长度更新标签回调内容
  2934. */
  2935. _measureUpdateLabelText: function() {
  2936. var self = this;
  2937. return function() {
  2938. if (self.measureAreaResult > 100000) {
  2939. return (self.measureAreaResult / 100000).toFixed(2) + "km²";
  2940. } else {
  2941. return self.measureAreaResult.toFixed(2) + "m²";
  2942. }
  2943. };
  2944. },
  2945. /**
  2946. * 测量面积点集合属性回调
  2947. */
  2948. _measureUpdatePolygon: function() {
  2949. var self = this;
  2950. return function() {
  2951. return {
  2952. positions: self.measurePoints,
  2953. };
  2954. };
  2955. },
  2956. /**
  2957. * 测量长度的鼠标移动事件
  2958. * @param {Object} event 事件
  2959. */
  2960. _eventMeasureLengthMouseMove: function(event) {
  2961. var self = this;
  2962. var ray = this.viewer.camera.getPickRay(event.endPosition);
  2963. var cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
  2964. if (self.measurePoints.length > 1) {
  2965. self.measurePoints.pop();
  2966. self.measurePoints.push(cartesian);
  2967. }
  2968. },
  2969. /**
  2970. * 测量结束事件
  2971. * @param {Object} event 事件
  2972. */
  2973. _eventMeasureEnd: function(event) {
  2974. this.actionType = ActionType.non;
  2975. this.measurePoints.pop();
  2976. this.viewer.scene.requestRenderMode = true; //停止主动刷新
  2977. //this.updateSence(); //主动刷新以下
  2978. },
  2979. /**
  2980. * 计算距离
  2981. * @param {Object} positions 点集合
  2982. */
  2983. _measureSpaceDistance: function(positions) {
  2984. var distance = 0;
  2985. for (var i = 0; i < positions.length - 1; i++) {
  2986. var point1cartographic = Cesium.Cartographic.fromCartesian(positions[i]);
  2987. var point2cartographic = Cesium.Cartographic.fromCartesian(positions[i + 1]);
  2988. /**根据经纬度计算出距**/
  2989. var geodesic = new Cesium.EllipsoidGeodesic();
  2990. geodesic.setEndPoints(point1cartographic, point2cartographic);
  2991. var s = geodesic.surfaceDistance;
  2992. //返回两点之间的距离
  2993. s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic
  2994. .height,
  2995. 2));
  2996. distance = distance + s;
  2997. }
  2998. if (distance < 1000) return distance.toFixed(2) + "米";
  2999. else return (distance / 1000).toFixed(2) + "公里";
  3000. },
  3001. /**
  3002. * 计算面积
  3003. * @param {Object} points 点集合
  3004. */
  3005. _measureArea: function(points) {
  3006. var self = this;
  3007. var res = 0;
  3008. // for (var i = 0; i < tempPoints.length; i++) {
  3009. // console.log("i = " + i + " value = " + JSON.stringify(tempPoints[i]));
  3010. // }
  3011. //拆分三角曲面
  3012. for (var i = 0; i < points.length - 2; i++) {
  3013. var j = (i + 1) % points.length;
  3014. var k = (i + 2) % points.length;
  3015. var totalAngle = self._measureAreaAngle(points[i], points[j], points[k]);
  3016. var dis_temp1 = self._measureAreaDistance(self.measurePoints[i], self.measurePoints[j]);
  3017. var dis_temp2 = self._measureAreaDistance(self.measurePoints[j], self.measurePoints[k]);
  3018. res += dis_temp1 * dis_temp2 * Math.abs(Math.sin(totalAngle));
  3019. // console.log(res);
  3020. }
  3021. return res;
  3022. },
  3023. /**
  3024. * 计算角度
  3025. * @param {Object} p1 点1
  3026. * @param {Object} p2 点2
  3027. * @param {Object} p3 点3
  3028. */
  3029. _measureAreaAngle: function(p1, p2, p3) {
  3030. var bearing21 = this._measureAreaBearing(p2, p1);
  3031. var bearing23 = this._measureAreaBearing(p2, p3);
  3032. var angle = bearing21 - bearing23;
  3033. if (angle < 0) {
  3034. angle += 360;
  3035. }
  3036. return angle;
  3037. },
  3038. /**
  3039. * 计算方向
  3040. * @param {Object} from 起始
  3041. * @param {Object} to 终止
  3042. */
  3043. _measureAreaBearing: function(from, to) {
  3044. var radiansPerDegree = Math.PI / 180.0; //角度转化为弧度(rad)
  3045. var degreesPerRadian = 180.0 / Math.PI; //弧度转化为角度
  3046. var lat1 = from.lat * radiansPerDegree;
  3047. var lon1 = from.lon * radiansPerDegree;
  3048. var lat2 = to.lat * radiansPerDegree;
  3049. var lon2 = to.lon * radiansPerDegree;
  3050. var angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2), Math.cos(lat1) * Math.sin(
  3051. lat2) -
  3052. Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2));
  3053. if (angle < 0) {
  3054. angle += Math.PI * 2.0;
  3055. }
  3056. angle = angle * degreesPerRadian; //角度
  3057. return angle;
  3058. },
  3059. /**
  3060. * 计算两点之间的距离
  3061. * @param {Object} point1 点1
  3062. * @param {Object} point2 点2
  3063. */
  3064. _measureAreaDistance(point1, point2) {
  3065. var point1cartographic = Cesium.Cartographic.fromCartesian(point1);
  3066. var point2cartographic = Cesium.Cartographic.fromCartesian(point2);
  3067. /**根据经纬度计算出距离**/
  3068. var geodesic = new Cesium.EllipsoidGeodesic();
  3069. geodesic.setEndPoints(point1cartographic, point2cartographic);
  3070. var s = geodesic.surfaceDistance;
  3071. //console.log(Math.sqrt(Math.pow(distance, 2) + Math.pow(endheight, 2)));
  3072. //返回两点之间的距离
  3073. s = Math.sqrt(Math.pow(s, 2) + Math.pow(point2cartographic.height - point1cartographic
  3074. .height, 2));
  3075. return s;
  3076. },
  3077. /**
  3078. * 清除测量结果
  3079. */
  3080. _measureRemoveResult: function() {
  3081. this._removeEntities('measure');
  3082. },
  3083. /**
  3084. * 测量初始化
  3085. */
  3086. _measureInit: function() {
  3087. this.measurePoints = []; //测量数组
  3088. this.measureTempPoints = []; //面积计算数组
  3089. this.measurePolyline = undefined; //测量线
  3090. this.measurePolygon = undefined; //测量线
  3091. this.measureDistanceResult = 0; //测量长度
  3092. this.measureAreaResult = 0; //测量面积
  3093. this._measureRemoveResult();
  3094. },
  3095. /**
  3096. * @param {string} callback 回调消息
  3097. */
  3098. measureLength: function(callback) {
  3099. this._measureInit();
  3100. this.actionType = ActionType.measureLength;
  3101. if (callback != undefined) {
  3102. callback("单击开始测量!");
  3103. }
  3104. },
  3105. /**
  3106. * @param {string} callback 回调消息
  3107. */
  3108. measureArea: function(callback) {
  3109. this._measureInit();
  3110. this.actionType = ActionType.measureArea;
  3111. if (callback != undefined) {
  3112. callback("单击开始面积测量!");
  3113. }
  3114. },
  3115. /**
  3116. * 测量初始化
  3117. * @param {function} callback 回调函数
  3118. */
  3119. measureClear: function(callback) {
  3120. this._measureInit();
  3121. this.actionType = ActionType.non;
  3122. if (callback != undefined) callback();
  3123. },
  3124. });
  3125. /**
  3126. * 路径飞行相关
  3127. */
  3128. CrMap.prototype.extend({
  3129. /**
  3130. *
  3131. */
  3132. _getMapCenter: function() {
  3133. /* 获取当前视图的可视范围 west西经 south南纬 east东经 north北纬 以弧度表示*/
  3134. var rectangle = this.viewer.camera.computeViewRectangle();
  3135. /* 计算中心点 */
  3136. var cGraphic = Cesium.Rectangle.center(rectangle);
  3137. /* 计算高度 */
  3138. var height = this.viewer.scene.globe.getHeight(cGraphic);
  3139. cGraphic.height = height;
  3140. /* 制图表达转换为笛卡尔坐标 */
  3141. var point = Cesium.Cartographic.toCartesian(cGraphic);
  3142. /* 笛卡尔坐标系转换为WGS84坐标系 */
  3143. var rg84Point = Cesium.Cartographic.fromCartesian(point);
  3144. /* 返回 */
  3145. return {
  3146. lng: (Cesium.Math.toDegrees(rectangle.west) + Cesium.Math.toDegrees(rectangle.east)) / 2,
  3147. lat: (Cesium.Math.toDegrees(rectangle.south) + Cesium.Math.toDegrees(rectangle.north)) / 2,
  3148. alt: rg84Point.height,
  3149. };
  3150. },
  3151. /**
  3152. * 计算当前相机位置基于给定基础点旋转一定角度后的位置信息
  3153. * @param {JSON} options
  3154. * {lng: lat: alt: angle:}
  3155. * return{x: y: z:}
  3156. */
  3157. _calculateCameraPosition: function(options) {
  3158. var self = this;
  3159. /* 两个点 */
  3160. var point = Cesium.Cartesian3.fromDegrees(options.lng, options.lat, options.alt);
  3161. var cameraPosition = self.viewer.camera.position;
  3162. /* 计算参考点的地面法向量 */
  3163. var chicB = Cesium.Cartographic.fromCartesian(point); //转成以弧度表示的数据
  3164. chicB.height = 0;
  3165. var dB = Cesium.Cartographic.toCartesian(chicB); //此点其实为地面点对应的投影平面上的点
  3166. //normalize 对输入的坐标进行标准化处理 subtract计算两个笛卡尔的分量差异
  3167. var normaB = Cesium.Cartesian3.normalize(Cesium.Cartesian3.subtract(dB, point, new Cesium
  3168. .Cartesian3()), new Cesium.Cartesian3());
  3169. /* 构造基于B的法向量旋转90度的矩阵 */
  3170. //计算表示围绕轴旋转的四元数
  3171. var Q = Cesium.Quaternion.fromAxisAngle(normaB, Cesium.Math.toRadians(options.angle));
  3172. //根据提供的四元数计算3x3旋转矩阵
  3173. var m3 = Cesium.Matrix3.fromQuaternion(Q);
  3174. //从Matrix3计算代表旋转的Matrix4
  3175. var m4 = Cesium.Matrix4.fromRotationTranslation(m3);
  3176. /* 计算相机相对于基础点的位置 */
  3177. var A1 = Cesium.Cartesian3.subtract(cameraPosition, point, new Cesium.Cartesian3());
  3178. /* 对计算后的点应用旋转矩阵 计算矩阵与 Cartesian3 的乘积*/
  3179. var p = Cesium.Matrix4.multiplyByPoint(m4, A1, new Cesium.Cartesian3());
  3180. /* 新相机位置的坐标 */
  3181. var p2 = Cesium.Cartesian3.add(p, point, new Cesium.Cartesian3());
  3182. return p2;
  3183. },
  3184. // lng: 117.981144,
  3185. // lat: 36.314221,
  3186. // alt: 300,
  3187. /**
  3188. * 开始路径飞行 为了尝试使用点击事件确定中心点 则改为利用屏幕坐标进行飞行
  3189. * @param {Object} event 鼠标点击事件
  3190. */
  3191. _startFlightAround: function(event) {
  3192. var self = this;
  3193. var ray = self.viewer.camera.getPickRay(event.position);
  3194. var cartesian = self.viewer.scene.globe.pick(ray, self.viewer.scene);
  3195. if (cartesian == undefined) {
  3196. return;
  3197. }
  3198. //世界坐标转地理坐标(弧度)
  3199. var cartographic = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian);
  3200. //弧度转换为度
  3201. var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math
  3202. .PI * 180
  3203. ];
  3204. if (self.flightListner == undefined) {
  3205. /* 设置当前时间为起始时间 */
  3206. var startTime = Cesium.JulianDate.fromDate(new Date());
  3207. /* 设置当前时间+1000秒为结束时间 */
  3208. var stopTime = Cesium.JulianDate.addSeconds(startTime, 1000, new Cesium.JulianDate());
  3209. /* 设置Cesium固定时钟的起始时间 */
  3210. self.viewer.clock.startTime = startTime.clone();
  3211. /* 设置Cesium固定时钟的终止时间 */
  3212. self.viewer.clock.stopTime = stopTime.clone();
  3213. /* 设置Cesium固定时钟的当前时间 */
  3214. self.viewer.clock.currentTime = startTime.clone();
  3215. /* UNBOUNDED到达终止时间后继续读秒 CLAMPED达到终止时间后停止 LOOP_STOP到达终止时间后重复 */
  3216. self.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED;
  3217. /* 用于确定每次通话需要多少时间的常数 */
  3218. self.viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK;
  3219. /* 设置动画监听 */
  3220. self.flightListner = function eventClock() {
  3221. var newPosition = self._calculateCameraPosition({
  3222. lng: point[0],
  3223. lat: point[1],
  3224. alt: 300,
  3225. angle: self.angle,
  3226. });
  3227. self.viewer.camera.setView({
  3228. destination: newPosition,
  3229. orientation: {
  3230. heading: Cesium.Math.toRadians(Cesium.Math.toDegrees(self.viewer
  3231. .camera
  3232. .heading) + self.angle),
  3233. pitch: self.viewer.camera.pitch,
  3234. }
  3235. });
  3236. }
  3237. self.viewer.clock.onTick.addEventListener(self.flightListner);
  3238. }
  3239. },
  3240. /**
  3241. * 调起环飞工具
  3242. */
  3243. flightAround: function() {
  3244. this.actionType = ActionType.flightAround;
  3245. }
  3246. });
  3247. /**
  3248. * 动态Div标签相关
  3249. */
  3250. CrMap.prototype.extend({
  3251. /**
  3252. * 向地图中添加标签
  3253. * @param {JSON} options 配置项
  3254. * title{string}:标题
  3255. * sup{string}:子标题
  3256. * lng{float}:经度
  3257. * lat{float}:纬度
  3258. * alt{float}:高度
  3259. */
  3260. appendLabelToMap: function(options) {
  3261. var self = this;
  3262. var points = [{
  3263. lng: options.lng,
  3264. lat: options.lat,
  3265. }];
  3266. self.calculateAltitude({
  3267. points: points,
  3268. success: function(heights) {
  3269. var screenPoint = self.wgs84ToScreen({
  3270. lng: options.lng,
  3271. lat: options.lat,
  3272. alt: heights[0],
  3273. });
  3274. // /* 添加一个点 用于验证位置是否正确 */
  3275. // var point = Cesium.Cartesian3.fromDegrees(options.lng, options.lat, heights[0]);
  3276. // var pointEntity = new Cesium.Entity({
  3277. // name: 'test',
  3278. // position: point,
  3279. // point: {
  3280. // color: Cesium.Color.CRIMSON,
  3281. // pixelSize: 9,
  3282. // outlineColor: Cesium.Color.ALICEBLUE,
  3283. // outlineWidth: 2
  3284. // }
  3285. // });
  3286. // console.log("实体数量 = " + self.entities.values.length + " 高度=" + heights[0]);
  3287. // self.entities.add(pointEntity);
  3288. // console.log("实体数量 = " + self.entities.values.length);
  3289. var airWindowId = options.id;
  3290. /* 判断该div是否存在 */
  3291. var objAirBubbleWindow = document.getElementById(airWindowId);
  3292. if (objAirBubbleWindow == null) {
  3293. /* 创建div */
  3294. objAirBubbleWindow = document.createElement('div');
  3295. objAirBubbleWindow.id = airWindowId;
  3296. objAirBubbleWindow.setAttribute('tag',
  3297. 'label'); //设置标识 为了在地图变化的时候能找到需要处理的Div
  3298. objAirBubbleWindow.className = 'jt-tooltip-popup';
  3299. objAirBubbleWindow.onclick = function() {
  3300. this.style.display = 'none';
  3301. }
  3302. /* 加入到页面 */
  3303. document.body.append(objAirBubbleWindow);
  3304. }
  3305. objAirBubbleWindow.style.display = 'flex';
  3306. var contentHtml = "";
  3307. /* 具体内容 */
  3308. contentHtml += "<div>";
  3309. contentHtml += "<span class='title'>" + options.title + "</span>";
  3310. contentHtml += "<div>";
  3311. contentHtml += "<span class='state'>" + options.state + "</span>";
  3312. contentHtml += "<span class='area'>" + options.area + "</span>";
  3313. contentHtml += "</div>";
  3314. contentHtml += "</div>";
  3315. /* 竖线 */
  3316. contentHtml += "<div></div>";
  3317. /* 底部小圆圈 */
  3318. contentHtml += "<div></div>";
  3319. /* 赋值 */
  3320. objAirBubbleWindow.innerHTML = contentHtml;
  3321. /* 赋值位置 */
  3322. objAirBubbleWindow.style.top = (screenPoint.y - objAirBubbleWindow
  3323. .clientHeight) + 'px';
  3324. objAirBubbleWindow.style.left = (screenPoint.x - objAirBubbleWindow
  3325. .clientWidth / 2) + 'px';
  3326. /* 存储地理位置 */
  3327. objAirBubbleWindow.setAttribute('location', options.lng + "," + options.lat +
  3328. "," + heights[0]);
  3329. }
  3330. });
  3331. },
  3332. /**
  3333. * 重置标签的位置
  3334. */
  3335. resetLabelLocation() {
  3336. /* 获取符合要求的全部标签 */
  3337. var labels = document.querySelectorAll("div[tag = 'label']");
  3338. for (var i = 0; i < labels.length; i++) {
  3339. var labelDom = labels[i];
  3340. if (labelDom.style.display != 'none') {
  3341. /* 说明该标签处于显示状态 获取存储的位置信息*/
  3342. var location = labelDom.getAttribute('location');
  3343. var res = this.wgs84ToScreen({
  3344. lng: location.split(',')[0],
  3345. lat: location.split(',')[1],
  3346. alt: location.split(',')[2],
  3347. });
  3348. labelDom.style.top = (res.y - labelDom.clientHeight) + 'px';
  3349. labelDom.style.left = (res.x - labelDom.clientWidth / 2) + 'px';
  3350. }
  3351. }
  3352. }
  3353. });
  3354. /**
  3355. * 设置纹理属性信息
  3356. */
  3357. Cesium.Material.PolylineTrailLinkType = 'PolylineTrailLink';
  3358. Cesium.Material.PolylineTrailLinkImage =
  3359. "./img/colors1.png";
  3360. Cesium.Material.PolylineTrailLinkSource = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
  3361. {\n\
  3362. czm_material material = czm_getDefaultMaterial(materialInput);\n\
  3363. vec2 st = materialInput.st;\n\
  3364. vec4 colorImage = texture2D(image, vec2(fract(-st.s - time), st.t));\n\
  3365. material.alpha = colorImage.a * color.a;\n\
  3366. material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
  3367. return material;\n\
  3368. }";
  3369. /**
  3370. * 将自定义纹理添加到纹理缓存中
  3371. */
  3372. Cesium.Material._materialCache.addMaterial(Cesium.Material.PolylineTrailLinkType, {
  3373. fabric: {
  3374. type: Cesium.Material.PolylineTrailLinkType,
  3375. uniforms: {
  3376. color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
  3377. image: Cesium.Material.PolylineTrailLinkImage,
  3378. time: 0
  3379. },
  3380. source: Cesium.Material.PolylineTrailLinkSource
  3381. },
  3382. translucent: function(material) {
  3383. return true;
  3384. }
  3385. });