controlPanel.vue 130 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851
  1. <template>
  2. <div id="controlPanelBox">
  3. <div>
  4. <div class="sceneNameBox">
  5. <div class="">
  6. 场景名称:
  7. <el-cascader
  8. :disabled="$route.query.sceneId != undefined"
  9. v-model="SceneValue"
  10. placeholder="试试搜索:距离"
  11. :options="SceneList"
  12. :props="{ expandTrigger: 'hover' }"
  13. @change="handleChange"
  14. filterable
  15. ></el-cascader>
  16. <el-tooltip
  17. v-if="SceneValue && dmsServerItem.functionalDefinition"
  18. :content="dmsServerItem.functionalDefinition"
  19. placement="bottom"
  20. :popper-style="{ maxWidth: '300px' }"
  21. >
  22. <el-icon
  23. style="margin-left: 1rem; width: 1rem; height: 1rem"
  24. v-show="SceneValue && dmsServerItem.functionalDefinition"
  25. ><QuestionFilled
  26. /></el-icon>
  27. </el-tooltip>
  28. </div>
  29. <div>
  30. <el-button type="primary" @click="sendGeometriesToBackend"
  31. >发送<i class="el-icon-s-promotion el-icon--right"></i
  32. ></el-button>
  33. </div>
  34. </div>
  35. <el-divider></el-divider>
  36. <div>元素个数:{{ SceneValue && dmsServerItem ? dmsServerItem.numberOf : "0" }}</div>
  37. <div>参数类型:{{ SceneValue && dmsServerItem ? dmsServerItem.elementTypes : "[]" }}</div>
  38. <div>接口地址:{{ SceneValue && dmsServerItem ? dmsServerItem.apiUrl : "/" }}</div>
  39. </div>
  40. <el-divider></el-divider>
  41. <div>
  42. <!-- 元素文本渲染和操作区域 -->
  43. <el-tabs tab-position="left" style="height: calc(100vh - 250px)" class="demo-tabs">
  44. <el-tab-pane label="入参">
  45. <div v-if="SceneValue && dmsServerItem && ifHasType('file')">
  46. <el-upload
  47. ref="sceneFileUpload"
  48. v-model:file-list="fileList"
  49. class="upload-demo"
  50. action=""
  51. accept=".geojson,.csv,.xlsx,.zip"
  52. :limit="1"
  53. :on-change="handleFileChange"
  54. :on-exceed="handleExceed"
  55. :on-remove="uploadRemove"
  56. :auto-upload="false"
  57. >
  58. <el-button type="primary">上传文件</el-button>
  59. </el-upload>
  60. </div>
  61. <div v-if="SceneValue && dmsServerItem">
  62. <div v-for="item in dmsServerItem.elementTypes" :key="item">
  63. <div
  64. v-if="SceneValue && dmsServerItem && selectOptions[item]"
  65. style="margin: 0.5rem 0"
  66. >
  67. {{ item }}:
  68. <el-input
  69. v-if="item === 'geocodeColumnKeyword' && isGeocodeImportZip"
  70. v-model="params[item]"
  71. placeholder="zip 内含多个表格时请手动输入列名"
  72. clearable
  73. style="width: 240px"
  74. @input="handleSelectChange(item, $event)"
  75. />
  76. <el-select
  77. v-else-if="selectOptions[item]"
  78. @change="handleSelectChange(item, $event)"
  79. v-model="params[item]"
  80. :placeholder="
  81. item === 'geocodeColumnKeyword' && (!selectOptions[item] || !selectOptions[item].length)
  82. ? '请先上传 csv / xlsx 解析列名'
  83. : '请选择' + item
  84. "
  85. style="width: 240px"
  86. :disabled="
  87. item === 'geocodeColumnKeyword' &&
  88. !isGeocodeImportZip &&
  89. (!selectOptions[item] || !selectOptions[item].length)
  90. "
  91. filterable
  92. clearable
  93. >
  94. <el-option
  95. v-for="item2 in selectOptions[item]"
  96. :key="item2.value"
  97. :label="item2.label"
  98. :value="item2.value"
  99. />
  100. </el-select>
  101. </div>
  102. <div
  103. v-if="
  104. ['lon', 'lat', 'lonKey', 'latKey', 'filePath', 'EPSILON', 'distance'].includes(
  105. item
  106. )
  107. "
  108. >
  109. {{ item }}:
  110. <el-input
  111. v-model="params[item]"
  112. @input="handleSelectChange(item, $event)"
  113. style="width: 240px"
  114. :placeholder="'请输入' + item"
  115. />
  116. </div>
  117. </div>
  118. </div>
  119. <div
  120. class="vueJsonEditor_box"
  121. v-show="
  122. SceneValue &&
  123. dmsServerItem &&
  124. (ifHasType('point') || ifHasType('polyline') || ifHasType('polygon'))
  125. "
  126. >
  127. <div class="vueJsonEditor_tools">
  128. <span
  129. v-if="jsonData && (jsonData.features || jsonData.geometry)"
  130. @click="showToMap(jsonData, 'input')"
  131. >渲染到地图中</span
  132. >
  133. <el-tooltip content="定位到当前入参渲染要素" placement="top">
  134. <span v-if="renderStatus.input" @click="locateRenderedGeojson('input')">
  135. 定位
  136. </span>
  137. </el-tooltip>
  138. <span @click="copyJsonData(jsonData)">copy</span>
  139. </div>
  140. <vue-json-editor
  141. :key="'json-input-editor-' + inputEditorKey"
  142. v-model="jsonData"
  143. :value="jsonData"
  144. :show-btns="false"
  145. :mode="'code'"
  146. :lang="'zh'"
  147. @json-change="handleJsonChange"
  148. >
  149. </vue-json-editor>
  150. </div>
  151. </el-tab-pane>
  152. <el-tab-pane label="返回">
  153. <div
  154. v-if="backData.message || backData.error"
  155. :style="{
  156. backgroundColor: backData.code === 200 ? '#67C23A' : '#F56C6C',
  157. color: '#fff',
  158. padding: '5px 10px',
  159. fontSize: '14px',
  160. }"
  161. >
  162. {{ backData.message || backData.error }}
  163. </div>
  164. <div class="vueJsonEditor_box" v-show="SceneValue && dmsServerItem">
  165. <div class="vueJsonEditor_tools">
  166. <span
  167. v-if="backData.content && (backData.content.features || backData.content.geometry)"
  168. @click="showToMap(backData.content, 'output')"
  169. >渲染到地图中</span
  170. >
  171. <el-tooltip content="定位到当前返回渲染要素" placement="top">
  172. <span v-if="renderStatus.output" @click="locateRenderedGeojson('output')">
  173. 定位
  174. </span>
  175. </el-tooltip>
  176. <span @click="copyJsonData(backData.content)">copy</span>
  177. </div>
  178. <vue-json-editor
  179. v-if="backData.content"
  180. :key="'json-output-editor-' + outputEditorKey"
  181. v-model="backData.content"
  182. :value="backData.content"
  183. @json-change="handleJsonChange2"
  184. :show-btns="false"
  185. :mode="'code'"
  186. :lang="'zh'"
  187. >
  188. </vue-json-editor></div
  189. ></el-tab-pane>
  190. </el-tabs>
  191. </div>
  192. <el-dialog
  193. v-model="propertyDialog.visible"
  194. title="要素属性"
  195. width="420px"
  196. draggable
  197. :modal="false"
  198. append-to-body
  199. class="feature-property-dialog"
  200. >
  201. <div class="feature-property-content">
  202. <div class="feature-property-tip">
  203. 支持直接编辑属性值,失焦后自动同步 JSON。选中地图上的点/线/面后,可按住顶点拖动以实时修改坐标(与右侧入参 JSON 同步)。
  204. </div>
  205. <div
  206. class="feature-property-item"
  207. v-for="item in propertyDialog.list"
  208. :key="'feature-property-' + item.id"
  209. >
  210. <div class="feature-property-row">
  211. <el-input
  212. v-model="item.editKey"
  213. class="feature-property-input feature-property-key-input"
  214. placeholder="属性名"
  215. @change="handlePropertyKeyChange(item)"
  216. />
  217. <el-button
  218. type="danger"
  219. plain
  220. size="small"
  221. class="feature-property-delete-btn"
  222. @click="deleteProperty(item)"
  223. >
  224. 删除
  225. </el-button>
  226. </div>
  227. <el-input
  228. v-model="item.editValue"
  229. class="feature-property-input"
  230. placeholder="属性值"
  231. @change="handlePropertyValueChange(item)"
  232. />
  233. </div>
  234. <el-empty
  235. v-if="!propertyDialog.list.length"
  236. description="当前要素无属性信息"
  237. :image-size="80"
  238. />
  239. </div>
  240. <template #footer>
  241. <div class="feature-property-footer">
  242. <el-button type="primary" plain @click="addProperty">+ 添加字段</el-button>
  243. <div class="feature-property-actions">
  244. <el-button link type="primary" @click="startEditGeometry">更改绘制</el-button>
  245. <el-button link type="danger" @click="deleteSelectedFeature">删除</el-button>
  246. </div>
  247. </div>
  248. </template>
  249. </el-dialog>
  250. <div
  251. v-if="hoverHint.visible"
  252. class="map-edit-hover-hint"
  253. :style="{ left: hoverHint.left + 'px', top: hoverHint.top + 'px' }"
  254. >
  255. {{ hoverHint.text }}
  256. </div>
  257. <!-- 绘制工具栏 -->
  258. <div
  259. class="toolbar"
  260. v-if="
  261. SceneValue &&
  262. dmsServerItem &&
  263. (ifHasType('point') || ifHasType('polyline') || ifHasType('polygon'))
  264. "
  265. >
  266. <div
  267. v-if="ifHasType('point')"
  268. class="tool-item"
  269. @click="activateDraw('point')"
  270. :class="{ active: currentTool === 'point' }"
  271. >
  272. 绘制点
  273. <el-tooltip
  274. content="绘制开关,蓝色状态代表开启,再次点击结束绘制,地图左键点击选点,"
  275. placement="right"
  276. >
  277. <el-icon style="width: 1rem; height: 1rem"><QuestionFilled /></el-icon>
  278. </el-tooltip>
  279. </div>
  280. <div
  281. v-if="ifHasType('polyline')"
  282. class="tool-item"
  283. @click="activateDraw('polyline')"
  284. :class="{ active: currentTool === 'polyline' }"
  285. >
  286. 绘制线<el-tooltip
  287. content="绘制线最少需要两个点,鼠标左键点击选点,点之间自动连线,鼠标右键结束绘制"
  288. placement="right"
  289. >
  290. <el-icon style="width: 1rem; height: 1rem"><QuestionFilled /></el-icon>
  291. </el-tooltip>
  292. </div>
  293. <div
  294. v-if="ifHasType('polygon')"
  295. class="tool-item"
  296. @click="activateDraw('polygon')"
  297. :class="{ active: currentTool === 'polygon' }"
  298. >
  299. 绘制面<el-tooltip
  300. content="绘制面最少需要三个点,鼠标左键点击选点,面自动必合,鼠标右键结束绘制"
  301. placement="right"
  302. >
  303. <el-icon style="width: 1rem; height: 1rem"><QuestionFilled /></el-icon>
  304. </el-tooltip>
  305. </div>
  306. <!-- <div class="tool-item" @click="startHoleDrawing" :class="{ active: isDrawingHole }">
  307. 绘制镂空
  308. </div> -->
  309. <div class="tool-item" @click="clearAll">清除所有</div>
  310. </div>
  311. </div>
  312. </template>
  313. <script>
  314. import * as XLSX from "xlsx";
  315. import wgn from "../../api/wgn";
  316. import { getFile } from "../../utils/request";
  317. import { WGN_SCENE_LIST } from "@/data/wgnSceneList";
  318. // 控制面板
  319. export default {
  320. name: "ControlPanel",
  321. // 2. 接收父组件传递的 props(单向数据流,子组件不能直接修改)
  322. props: {
  323. btnText: {
  324. type: String, // 类型限制
  325. default: "默认按钮", // 默认值
  326. required: false, // 是否必传
  327. },
  328. showCount: {
  329. type: Boolean,
  330. default: false,
  331. },
  332. },
  333. data() {
  334. return {
  335. currentFile: null, // 当前选中的文件
  336. fileList: [],
  337. // 其他参数
  338. params: {
  339. unit: "",
  340. outFileType: "",
  341. outPrj: "",
  342. inPrj: "",
  343. compressionRatio: "",
  344. lon: "",
  345. lat: "",
  346. // 非空转空时,类型字段下拉选择[地址\村居\街镇\区县\要素ID]
  347. keyType: "",
  348. // 非空转空时,上传文件解析csv或xlsx文件后,渲染列名到下拉选择框中,指定某列作为类型字段
  349. geocodeColumnKeyword: "",
  350. },
  351. // 请求参数
  352. jsonData: {},
  353. // 返回参数
  354. backData: {},
  355. // 当前场景值
  356. SceneValue: "",
  357. // 场景列表(与微功能中心侧栏同源)
  358. SceneList: WGN_SCENE_LIST,
  359. dmsServerItem: {},
  360. selectOptions: {
  361. // 单位
  362. unit: [
  363. {
  364. value: "METER",
  365. label: "米",
  366. },
  367. {
  368. value: "KILOMETER",
  369. label: "千米",
  370. },
  371. ],
  372. inPrj: [
  373. {
  374. value: "WGS84",
  375. label: "WGS84",
  376. },
  377. {
  378. value: "SH2000",
  379. label: "SH2000",
  380. },
  381. {
  382. value: "UTM",
  383. label: "UTM",
  384. },
  385. {
  386. value: "WEB_Mercator",
  387. label: "WEB_Mercator",
  388. },
  389. ],
  390. compressionRatio: [
  391. {
  392. value: "100%",
  393. label: "100%",
  394. },
  395. {
  396. value: "80%",
  397. label: "80%",
  398. },
  399. {
  400. value: "50%",
  401. label: "50%",
  402. },
  403. {
  404. value: "25%",
  405. label: "25%",
  406. },
  407. ],
  408. outPrj: [
  409. {
  410. value: "WGS84",
  411. label: "WGS84",
  412. },
  413. {
  414. value: "SH2000",
  415. label: "SH2000",
  416. },
  417. {
  418. value: "UTM",
  419. label: "UTM",
  420. },
  421. {
  422. value: "WEB_Mercator",
  423. label: "WEB_Mercator",
  424. },
  425. ],
  426. outFileType: [
  427. {
  428. value: "geoJson",
  429. label: "geoJson",
  430. },
  431. {
  432. value: "shp",
  433. label: "shp",
  434. },
  435. {
  436. value: "csv",
  437. label: "csv",
  438. },
  439. {
  440. value: "xlsx",
  441. label: "xlsx",
  442. },
  443. ],
  444. keyType: [
  445. { value: "地址", label: "地址" },
  446. { value: "村居", label: "村居" },
  447. { value: "街镇", label: "街镇" },
  448. { value: "区县", label: "区县" },
  449. // { value: "要素ID", label: "要素ID" },
  450. ],
  451. geocodeColumnKeyword: [],
  452. },
  453. currentTool: null,
  454. drawingMode: null,
  455. handler: null,
  456. drawnEntities: [],
  457. geometries: [], // 存储绘制的几何对象
  458. // 绘制状态相关
  459. currentEntity: null, // 当前正在绘制的实体
  460. currentPositions: [], // 当前正在绘制的位置数组
  461. isDrawingHole: false, // 是否正在绘制镂空
  462. currentPolygonEntity: null, // 当前要添加镂空的多边形实体
  463. currentPolygonGeometry: null, // 当前要添加镂空的多边形几何对象
  464. tempEntity: null, // 临时预览实体
  465. // 地图渲染状态(入参/返回)
  466. renderStatus: {
  467. input: false,
  468. output: false,
  469. },
  470. // 缓存两侧最近一次成功渲染的geojson,用于定位时恢复
  471. renderedGeojsonCache: {
  472. input: null,
  473. output: null,
  474. },
  475. currentRenderedSource: "",
  476. // 地图点击属性弹窗
  477. featurePickHandler: null,
  478. inputEditorKey: 0,
  479. outputEditorKey: 0,
  480. propertyIdSeed: 1,
  481. propertyDialog: {
  482. visible: false,
  483. list: [],
  484. source: "",
  485. propertiesRef: null,
  486. featureIndex: -1,
  487. },
  488. /** 地图编辑选中:高亮要素 + 顶点柄 */
  489. mapEditSelection: null,
  490. vertexHandleEntities: [],
  491. hoveredVertexIndex: -1,
  492. hoveredHandleEntity: null,
  493. hoveredFeatureEntity: null,
  494. geometryEditMode: false,
  495. pickedFeatureRef: null,
  496. hoverHint: {
  497. visible: false,
  498. text: "",
  499. left: 0,
  500. top: 0,
  501. },
  502. /** 拖动/绘制时临时关闭 requestRenderMode,避免面片异步剖分导致与顶点不同步 */
  503. _interactiveRenderDepth: 0,
  504. _savedSceneRenderMode: null,
  505. };
  506. },
  507. computed: {
  508. /** zip 多表场景下列名无法预解析,改用手动输入 */
  509. isGeocodeImportZip() {
  510. const f = this.currentFile;
  511. const name = f ? f.name || (f.raw && f.raw.name) || "" : "";
  512. return String(name).toLowerCase().endsWith(".zip");
  513. },
  514. },
  515. mounted() {
  516. this.SceneValue = this.$route.query.sceneId ? this.$route.query.sceneId : "";
  517. },
  518. beforeUnmount() {
  519. // 组件卸载前清理资源
  520. this.deactivateDraw();
  521. if (this.handler) {
  522. this.handler.destroy();
  523. }
  524. if (this.featurePickHandler) {
  525. this.featurePickHandler.destroy();
  526. this.featurePickHandler = null;
  527. }
  528. this.resetPickDragState();
  529. this.setScreenSpaceCameraForDrag(true);
  530. while (this._interactiveRenderDepth > 0) {
  531. this.exitInteractiveSceneRender();
  532. }
  533. },
  534. watch: {
  535. SceneValue(newVal, oldVal) {
  536. if (newVal && newVal != oldVal) {
  537. // 请求DMS
  538. this.searchServerList(this.SceneValue);
  539. }
  540. },
  541. dmsServerItem: {
  542. handler() {
  543. this.$nextTick(() => this.syncDrawToolWithElementTypes());
  544. },
  545. deep: true,
  546. },
  547. },
  548. methods: {
  549. /** 与 DMS 入参规则 c_input_parameter_rules 解析后的 elementTypes 对齐,支持少量别名 */
  550. expandParameterTypeAliases(type) {
  551. const aliases = [type, type + "Z"];
  552. if (type === "polyline") {
  553. aliases.push("line", "lineZ", "LineString", "LineStringZ");
  554. }
  555. if (type === "polygon") {
  556. aliases.push("multipolygon", "MultiPolygon", "MultiPolygonZ");
  557. }
  558. return aliases;
  559. },
  560. /**
  561. * 当前场景在指定几何槽位是否声明了 Z 型参数(如 pointZ、polylineZ、polygonZ 及别名 lineZ 等)。
  562. * 仅该槽位绘制出的坐标使用 [lon, lat, z]。
  563. */
  564. elementTypesHasZVariant(geometryCanon) {
  565. if (
  566. !this.dmsServerItem ||
  567. !Array.isArray(this.dmsServerItem.elementTypes) ||
  568. !geometryCanon
  569. ) {
  570. return false;
  571. }
  572. const zCandidates = this.expandParameterTypeAliases(geometryCanon).filter((a) =>
  573. String(a).toLowerCase().endsWith("z")
  574. );
  575. if (zCandidates.length === 0) {
  576. return false;
  577. }
  578. const declared = this.dmsServerItem.elementTypes.map((t) => String(t).toLowerCase());
  579. return zCandidates.some((c) => declared.includes(String(c).toLowerCase()));
  580. },
  581. /** 按几何槽位(point / polyline / polygon)生成 GeoJSON 坐标:含 Z 型参数时为 [lon, lat, z] */
  582. lonLatToGeoJsonCoord(lon, lat, geometryCanon, z = 0) {
  583. if (geometryCanon && this.elementTypesHasZVariant(geometryCanon)) {
  584. return [lon, lat, z];
  585. }
  586. return [lon, lat];
  587. },
  588. ifHasType(type) {
  589. if (
  590. !this.dmsServerItem ||
  591. !this.dmsServerItem.elementTypes ||
  592. this.dmsServerItem.elementTypes.length === 0
  593. ) {
  594. return false;
  595. }
  596. const declared = this.dmsServerItem.elementTypes;
  597. const candidates = this.expandParameterTypeAliases(type);
  598. return declared.some((t) => candidates.includes(t));
  599. },
  600. /** DMS 声明的单个参数是否属于点/线/面几何槽位,返回规范名 point | polyline | polygon */
  601. geometrySlotCanonical(declaredType) {
  602. if (declaredType == null || declaredType === "") {
  603. return null;
  604. }
  605. const d = String(declaredType);
  606. for (const canon of ["point", "polyline", "polygon"]) {
  607. const aliases = this.expandParameterTypeAliases(canon);
  608. const hit = aliases.some(
  609. (a) => String(a) === d || String(a).toLowerCase() === d.toLowerCase()
  610. );
  611. if (hit) {
  612. return canon;
  613. }
  614. }
  615. return null;
  616. },
  617. /** GeoJSON geometry.type -> 与 geometrySlotCanonical 同一套规范名 */
  618. featureGeometryCanonical(geoJsonType) {
  619. if (!geoJsonType) {
  620. return null;
  621. }
  622. const t = String(geoJsonType);
  623. if (t === "Point") {
  624. return "point";
  625. }
  626. if (t === "LineString" || t === "MultiLineString") {
  627. return "polyline";
  628. }
  629. if (t === "Polygon" || t === "MultiPolygon") {
  630. return "polygon";
  631. }
  632. return null;
  633. },
  634. /**
  635. * 发送前校验:当「元素个数」numberOf > 0 时,与入参 FeatureCollection.features 数量对齐;
  636. * numberOf 为 0 时表示几何要素个数不固定(支持多个),不拦截数量。
  637. * 「参数类型」elementTypes 中的 point/polyline/polygon 仅表示允许的几何类型(可多选),
  638. * 不要求每种类型各来一个,也不要求与声明顺序一一对应(忽略 unit/file 等非几何项)。
  639. */
  640. validateSendGeometryParams() {
  641. if (!this.dmsServerItem || !Array.isArray(this.dmsServerItem.elementTypes)) {
  642. return { ok: true };
  643. }
  644. const types = this.dmsServerItem.elementTypes;
  645. const geoSlots = types
  646. .map((declared) => ({
  647. declared,
  648. canon: this.geometrySlotCanonical(declared),
  649. }))
  650. .filter((s) => s.canon != null);
  651. if (geoSlots.length === 0) {
  652. return { ok: true };
  653. }
  654. const allowedCanonSet = new Set(geoSlots.map((s) => s.canon));
  655. const rawN = this.dmsServerItem.numberOf;
  656. let expectedGeomCount = null;
  657. if (rawN !== undefined && rawN !== null && rawN !== "") {
  658. const parsedN = typeof rawN === "number" ? rawN : Number(rawN);
  659. // 0 表示不固定个数、支持多个要素,不做「元素个数」与 features 数量对齐拦截
  660. if (Number.isFinite(parsedN) && parsedN > 0) {
  661. expectedGeomCount = parsedN;
  662. }
  663. }
  664. const fc = this.jsonData;
  665. const features = fc && Array.isArray(fc.features) ? fc.features : [];
  666. if (expectedGeomCount !== null) {
  667. if (features.length > expectedGeomCount) {
  668. return {
  669. ok: false,
  670. message: `入参几何要素过多:当前 ${features.length} 个,场景要求 ${expectedGeomCount} 个(元素个数)`,
  671. };
  672. }
  673. if (features.length < expectedGeomCount) {
  674. return {
  675. ok: false,
  676. message: `入参几何要素不足:当前 ${features.length} 个,场景要求 ${expectedGeomCount} 个(元素个数),请绘制或渲染足够要素`,
  677. };
  678. }
  679. }
  680. for (let i = 0; i < features.length; i++) {
  681. const f = features[i];
  682. const g = f && f.geometry;
  683. if (!g || !g.type) {
  684. return {
  685. ok: false,
  686. message: `第 ${i + 1} 个几何要素缺少有效的 geometry`,
  687. };
  688. }
  689. const fk = this.featureGeometryCanonical(g.type);
  690. if (!fk) {
  691. return {
  692. ok: false,
  693. message: `第 ${i + 1} 个几何要素类型「${g.type}」不符合场景要求,请使用点、线或面`,
  694. };
  695. }
  696. if (!allowedCanonSet.has(fk)) {
  697. const allowedLabel = [...allowedCanonSet].join("、");
  698. return {
  699. ok: false,
  700. message: `第 ${i + 1} 个几何要素类型「${g.type}」不在场景允许的类型内,允许:${allowedLabel}`,
  701. };
  702. }
  703. }
  704. return { ok: true };
  705. },
  706. /** 场景切换后若当前绘制类型不在参数类型中,则关闭绘制避免“隐形”仍在绘制 */
  707. syncDrawToolWithElementTypes() {
  708. if (!this.currentTool) {
  709. return;
  710. }
  711. const t = this.currentTool;
  712. if (t === "point" && !this.ifHasType("point")) {
  713. this.deactivateDraw();
  714. } else if (t === "polyline" && !this.ifHasType("polyline")) {
  715. this.deactivateDraw();
  716. } else if (t === "polygon" && !this.ifHasType("polygon")) {
  717. this.deactivateDraw();
  718. }
  719. },
  720. handleJsonChange(jsonStr) {
  721. this.jsonData = jsonStr;
  722. },
  723. handleJsonChange2(jsonStr) {
  724. this.backData.content = jsonStr;
  725. },
  726. // 搜索微功能服务
  727. searchServerList() {
  728. let requestParams = {
  729. columnId: systemConfig.columnIds[5],
  730. states: 0,
  731. pageSize: 999,
  732. page: 0,
  733. };
  734. if (this.SceneValue) {
  735. requestParams.search = JSON.stringify([
  736. {
  737. field: "c_scene_name",
  738. searchType: 1,
  739. content: { value: this.SceneValue },
  740. },
  741. ]);
  742. // 获取微功能服务列表
  743. wgn
  744. .getDmsData(requestParams)
  745. .then((res) => {
  746. if (res.code === 200 && res.content.data[0]) {
  747. let dmsServiceData = res.content.data[0];
  748. this.dmsServerItem = {
  749. // 功能描述
  750. functionalDefinition: dmsServiceData.content,
  751. // 元素类型
  752. elementTypes: JSON.parse(dmsServiceData.c_input_parameter_rules),
  753. // 元素个数
  754. numberOf: JSON.parse(dmsServiceData.c_number_of_elements),
  755. // 后台接口路径
  756. apiUrl: dmsServiceData.c_url,
  757. };
  758. } else {
  759. this.$message({
  760. message: "搜索微功能服务失败,请检查场景名称是否正确",
  761. type: "warning",
  762. });
  763. }
  764. })
  765. .catch((e) => {
  766. this.$message({
  767. message: "搜索微功能服务失败" + e,
  768. type: "error",
  769. });
  770. });
  771. }
  772. },
  773. getSourceGeojsonData(source) {
  774. return source === "output" ? this.backData.content : this.jsonData;
  775. },
  776. syncGeometriesFromRenderedSource() {
  777. const src = this.currentRenderedSource || "input";
  778. const geojson = this.getSourceGeojsonData(src);
  779. if (!geojson) {
  780. return;
  781. }
  782. const list = [];
  783. if (geojson.features && Array.isArray(geojson.features)) {
  784. geojson.features.forEach((f) => {
  785. if (f && f.geometry && f.geometry.type && f.geometry.coordinates) {
  786. list.push({
  787. type: f.geometry.type,
  788. coordinates: JSON.parse(JSON.stringify(f.geometry.coordinates)),
  789. });
  790. }
  791. });
  792. } else if (geojson.geometry && geojson.geometry.type && geojson.geometry.coordinates) {
  793. list.push({
  794. type: geojson.geometry.type,
  795. coordinates: JSON.parse(JSON.stringify(geojson.geometry.coordinates)),
  796. });
  797. }
  798. if (list.length) {
  799. this.geometries = list;
  800. }
  801. },
  802. // 将用户输入或后台返回的geojson渲染到地图中
  803. showToMap(geojson, source = "input") {
  804. if (!geojson || (!geojson.features && !geojson.geometry)) {
  805. this.$message({
  806. message: "当前JSON缺少有效几何信息,无法渲染",
  807. type: "warning",
  808. });
  809. return;
  810. }
  811. this.currentRenderedSource = source;
  812. // 1. 清除所有地图中的元素
  813. this.clearAllMap();
  814. // 2. 将geojson添加到地图中
  815. this.addToMap(geojson);
  816. this.currentRenderedSource = source;
  817. this.renderStatus[source] = true;
  818. // 仅缓存纯数据,避免响应式对象带来的引用副作用
  819. this.renderedGeojsonCache[source] = JSON.parse(JSON.stringify(geojson));
  820. this.flyToGeojson(geojson);
  821. },
  822. // 定位到已渲染要素
  823. locateRenderedGeojson(source) {
  824. if (!this.renderStatus[source]) {
  825. return;
  826. }
  827. // 当前地图不是该来源数据时,优先恢复对应渲染结果,再飞行定位
  828. if (this.currentRenderedSource !== source && this.renderedGeojsonCache[source]) {
  829. this.showToMap(this.renderedGeojsonCache[source], source);
  830. return;
  831. }
  832. const sourceGeojson = this.getSourceGeojsonData(source) || this.renderedGeojsonCache[source];
  833. this.flyToGeojson(sourceGeojson);
  834. },
  835. collectGeometryCoordinates(geometry) {
  836. if (!geometry || !geometry.coordinates) {
  837. return [];
  838. }
  839. const { type, coordinates } = geometry;
  840. const points = [];
  841. if (type === "Point") {
  842. points.push([coordinates[0], coordinates[1]]);
  843. } else if (type === "LineString") {
  844. coordinates.forEach((coord) => points.push([coord[0], coord[1]]));
  845. } else if (type === "Polygon") {
  846. coordinates.forEach((ring) => {
  847. ring.forEach((coord) => points.push([coord[0], coord[1]]));
  848. });
  849. } else if (type === "MultiPolygon") {
  850. coordinates.forEach((polygon) => {
  851. polygon.forEach((ring) => {
  852. ring.forEach((coord) => points.push([coord[0], coord[1]]));
  853. });
  854. });
  855. }
  856. return points;
  857. },
  858. collectGeojsonCoordinates(geojson) {
  859. if (!geojson) {
  860. return [];
  861. }
  862. if (geojson.features && Array.isArray(geojson.features)) {
  863. return geojson.features.flatMap((feature) =>
  864. this.collectGeometryCoordinates(feature.geometry)
  865. );
  866. }
  867. if (geojson.geometry) {
  868. return this.collectGeometryCoordinates(geojson.geometry);
  869. }
  870. return [];
  871. },
  872. // 飞行定位到geojson范围
  873. flyToGeojson(geojson) {
  874. if (!viewer || !geojson) {
  875. return;
  876. }
  877. const points = this.collectGeojsonCoordinates(geojson);
  878. if (!points.length) {
  879. return;
  880. }
  881. if (points.length === 1) {
  882. viewer.camera.flyTo({
  883. destination: SkyScenery.Cartesian3.fromDegrees(points[0][0], points[0][1], 1200),
  884. duration: 1.1,
  885. orientation: {
  886. heading: viewer.camera.heading,
  887. pitch: SkyScenery.Math.toRadians(-65),
  888. roll: 0,
  889. },
  890. });
  891. viewer.scene.requestRender();
  892. return;
  893. }
  894. let minLon = Infinity;
  895. let maxLon = -Infinity;
  896. let minLat = Infinity;
  897. let maxLat = -Infinity;
  898. points.forEach((point) => {
  899. minLon = Math.min(minLon, point[0]);
  900. maxLon = Math.max(maxLon, point[0]);
  901. minLat = Math.min(minLat, point[1]);
  902. maxLat = Math.max(maxLat, point[1]);
  903. });
  904. const lonPad = Math.max((maxLon - minLon) * 0.25, 0.0008);
  905. const latPad = Math.max((maxLat - minLat) * 0.25, 0.0008);
  906. viewer.camera.flyTo({
  907. destination: SkyScenery.Rectangle.fromDegrees(
  908. minLon - lonPad,
  909. minLat - latPad,
  910. maxLon + lonPad,
  911. maxLat + latPad
  912. ),
  913. duration: 1.1,
  914. });
  915. viewer.scene.requestRender();
  916. },
  917. // 把属性对象格式化为可编辑列表
  918. formatFeatureProperties(properties) {
  919. if (!properties || typeof properties !== "object") {
  920. return [];
  921. }
  922. return Object.keys(properties).map((key) => {
  923. const rawValue = properties[key];
  924. const editValue =
  925. rawValue === null || rawValue === undefined
  926. ? ""
  927. : typeof rawValue === "object"
  928. ? JSON.stringify(rawValue)
  929. : String(rawValue);
  930. return {
  931. id: this.propertyIdSeed++,
  932. originalKey: key,
  933. editKey: key,
  934. editValue,
  935. };
  936. });
  937. },
  938. parsePropertyValue(inputValue) {
  939. if (typeof inputValue !== "string") {
  940. return inputValue;
  941. }
  942. const value = inputValue.trim();
  943. if (value === "") {
  944. return "";
  945. }
  946. if (value === "true") {
  947. return true;
  948. }
  949. if (value === "false") {
  950. return false;
  951. }
  952. if (value === "null") {
  953. return null;
  954. }
  955. if (!isNaN(Number(value))) {
  956. return Number(value);
  957. }
  958. if (
  959. (value.startsWith("{") && value.endsWith("}")) ||
  960. (value.startsWith("[") && value.endsWith("]"))
  961. ) {
  962. try {
  963. return JSON.parse(value);
  964. } catch (e) {
  965. return inputValue;
  966. }
  967. }
  968. return inputValue;
  969. },
  970. syncJsonEditorData(source) {
  971. if (source === "output") {
  972. if (!this.backData.content) {
  973. return;
  974. }
  975. this.backData = {
  976. ...this.backData,
  977. content: JSON.parse(JSON.stringify(this.backData.content)),
  978. };
  979. } else {
  980. this.jsonData = JSON.parse(JSON.stringify(this.jsonData));
  981. }
  982. if (source === "output") {
  983. this.outputEditorKey += 1;
  984. } else {
  985. this.inputEditorKey += 1;
  986. }
  987. this.renderedGeojsonCache[source] = JSON.parse(
  988. JSON.stringify(this.getSourceGeojsonData(source))
  989. );
  990. const latestGeojson = this.getSourceGeojsonData(source);
  991. if (latestGeojson && this.propertyDialog.visible && this.propertyDialog.source === source) {
  992. if (
  993. this.propertyDialog.featureIndex >= 0 &&
  994. latestGeojson.features &&
  995. latestGeojson.features[this.propertyDialog.featureIndex]
  996. ) {
  997. if (!latestGeojson.features[this.propertyDialog.featureIndex].properties) {
  998. latestGeojson.features[this.propertyDialog.featureIndex].properties = {};
  999. }
  1000. this.propertyDialog.propertiesRef =
  1001. latestGeojson.features[this.propertyDialog.featureIndex].properties;
  1002. } else {
  1003. if (!latestGeojson.properties) {
  1004. latestGeojson.properties = {};
  1005. }
  1006. this.propertyDialog.propertiesRef = latestGeojson.properties;
  1007. }
  1008. }
  1009. },
  1010. handlePropertyValueChange(item) {
  1011. if (!this.propertyDialog.propertiesRef || !item) {
  1012. return;
  1013. }
  1014. const currentKey = (item.editKey || "").trim();
  1015. if (!currentKey) {
  1016. this.$message({
  1017. message: "属性名不能为空",
  1018. type: "warning",
  1019. });
  1020. item.editKey = item.originalKey || "";
  1021. return;
  1022. }
  1023. this.propertyDialog.propertiesRef[currentKey] = this.parsePropertyValue(item.editValue);
  1024. item.originalKey = currentKey;
  1025. item.editKey = currentKey;
  1026. this.syncPropertyToEntity(this.propertyDialog.propertiesRef);
  1027. this.syncJsonEditorData(this.propertyDialog.source || this.currentRenderedSource || "input");
  1028. },
  1029. handlePropertyKeyChange(item) {
  1030. if (!this.propertyDialog.propertiesRef || !item) {
  1031. return;
  1032. }
  1033. const oldKey = item.originalKey;
  1034. const newKey = (item.editKey || "").trim();
  1035. if (!newKey) {
  1036. this.$message({
  1037. message: "属性名不能为空",
  1038. type: "warning",
  1039. });
  1040. item.editKey = oldKey;
  1041. return;
  1042. }
  1043. if (
  1044. newKey !== oldKey &&
  1045. Object.prototype.hasOwnProperty.call(this.propertyDialog.propertiesRef, newKey)
  1046. ) {
  1047. this.$message({
  1048. message: "属性名已存在,请更换",
  1049. type: "warning",
  1050. });
  1051. item.editKey = oldKey;
  1052. return;
  1053. }
  1054. const oldValue = this.propertyDialog.propertiesRef[oldKey];
  1055. if (newKey !== oldKey) {
  1056. delete this.propertyDialog.propertiesRef[oldKey];
  1057. this.propertyDialog.propertiesRef[newKey] = oldValue;
  1058. }
  1059. item.originalKey = newKey;
  1060. item.editKey = newKey;
  1061. this.syncPropertyToEntity(this.propertyDialog.propertiesRef);
  1062. this.syncJsonEditorData(this.propertyDialog.source || this.currentRenderedSource || "input");
  1063. },
  1064. deleteProperty(item) {
  1065. if (!this.propertyDialog.propertiesRef || !item) {
  1066. return;
  1067. }
  1068. const key = (item.originalKey || "").trim();
  1069. if (key && Object.prototype.hasOwnProperty.call(this.propertyDialog.propertiesRef, key)) {
  1070. delete this.propertyDialog.propertiesRef[key];
  1071. }
  1072. this.propertyDialog.list = this.propertyDialog.list.filter(
  1073. (property) => property.id !== item.id
  1074. );
  1075. this.syncPropertyToEntity(this.propertyDialog.propertiesRef);
  1076. this.syncJsonEditorData(this.propertyDialog.source || this.currentRenderedSource || "input");
  1077. },
  1078. addProperty() {
  1079. if (!this.propertyDialog.propertiesRef) {
  1080. this.$message({
  1081. message: "请先点击地图中的已渲染要素",
  1082. type: "warning",
  1083. });
  1084. return;
  1085. }
  1086. let index = 1;
  1087. let newKey = "newKey";
  1088. while (Object.prototype.hasOwnProperty.call(this.propertyDialog.propertiesRef, newKey)) {
  1089. newKey = `newKey${index}`;
  1090. index += 1;
  1091. }
  1092. this.propertyDialog.propertiesRef[newKey] = "";
  1093. this.propertyDialog.list.push({
  1094. id: this.propertyIdSeed++,
  1095. originalKey: newKey,
  1096. editKey: newKey,
  1097. editValue: "",
  1098. });
  1099. this.syncPropertyToEntity(this.propertyDialog.propertiesRef);
  1100. this.syncJsonEditorData(this.propertyDialog.source || this.currentRenderedSource || "input");
  1101. },
  1102. startEditGeometry() {
  1103. const picked = this.pickedFeatureRef;
  1104. if (!picked || !picked.entity) {
  1105. this.$message({
  1106. message: "请先选择要素",
  1107. type: "warning",
  1108. });
  1109. return;
  1110. }
  1111. this.geometryEditMode = true;
  1112. this.deactivateDraw();
  1113. this.applyMapEditSelection(picked.entity);
  1114. this.propertyDialog.visible = false;
  1115. this.$message({
  1116. message: "已进入节点编辑模式,可拖拽顶点或中点调整绘制",
  1117. type: "success",
  1118. });
  1119. },
  1120. reindexEntityFeatureRefs(source, deletedIndex) {
  1121. this.drawnEntities.forEach((ent) => {
  1122. if (!ent || !ent.__featureRef) return;
  1123. if (
  1124. ent.__featureRef.source === source &&
  1125. typeof ent.__featureRef.featureIndex === "number" &&
  1126. ent.__featureRef.featureIndex > deletedIndex
  1127. ) {
  1128. ent.__featureRef.featureIndex -= 1;
  1129. }
  1130. });
  1131. },
  1132. deleteSelectedFeature() {
  1133. const sel = this.mapEditSelection || this.pickedFeatureRef;
  1134. if (!sel || !sel.entity || sel.featureIndex < 0) {
  1135. this.$message({
  1136. message: "请先选择要素",
  1137. type: "warning",
  1138. });
  1139. return;
  1140. }
  1141. const source = sel.source || this.currentRenderedSource || "input";
  1142. const geojson = this.getSourceGeojsonData(source);
  1143. if (!geojson || !geojson.features || !Array.isArray(geojson.features)) {
  1144. this.$message({
  1145. message: "当前数据不是 FeatureCollection,无法删除",
  1146. type: "warning",
  1147. });
  1148. return;
  1149. }
  1150. const idx = sel.featureIndex;
  1151. if (idx < 0 || idx >= geojson.features.length) {
  1152. this.$message({
  1153. message: "要素索引无效,删除失败",
  1154. type: "error",
  1155. });
  1156. return;
  1157. }
  1158. geojson.features.splice(idx, 1);
  1159. const toRemove = this.drawnEntities.filter(
  1160. (ent) =>
  1161. ent &&
  1162. ent.__featureRef &&
  1163. ent.__featureRef.source === source &&
  1164. ent.__featureRef.featureIndex === idx
  1165. );
  1166. toRemove.forEach((ent) => {
  1167. try {
  1168. viewer.entities.remove(ent);
  1169. } catch (e) {
  1170. /* ignore */
  1171. }
  1172. });
  1173. this.drawnEntities = this.drawnEntities.filter((ent) => !toRemove.includes(ent));
  1174. this.reindexEntityFeatureRefs(source, idx);
  1175. this.propertyDialog.visible = false;
  1176. this.propertyDialog.list = [];
  1177. this.propertyDialog.source = "";
  1178. this.propertyDialog.propertiesRef = null;
  1179. this.propertyDialog.featureIndex = -1;
  1180. this.clearMapEditSelection();
  1181. this.syncJsonEditorData(source);
  1182. this.$message({
  1183. message: "删除成功",
  1184. type: "success",
  1185. });
  1186. },
  1187. syncPropertyToEntity(propertiesRef) {
  1188. if (!propertiesRef || !viewer || !this.currentRenderedSource) {
  1189. return;
  1190. }
  1191. const targetSource = this.propertyDialog.source || this.currentRenderedSource;
  1192. const targetIndex = this.propertyDialog.featureIndex;
  1193. this.drawnEntities.forEach((entity) => {
  1194. if (!entity || !entity.__featureRef) {
  1195. return;
  1196. }
  1197. if (
  1198. entity.__featureRef.source === targetSource &&
  1199. entity.__featureRef.featureIndex === targetIndex
  1200. ) {
  1201. entity.__featureProperties = propertiesRef;
  1202. }
  1203. });
  1204. },
  1205. // 将geojson添加到地图中
  1206. addToMap(geojson) {
  1207. const source = this.currentRenderedSource || "input";
  1208. if (!geojson.features && geojson.geometry) {
  1209. const { type, coordinates } = geojson.geometry;
  1210. const featureProperties = geojson.properties || {};
  1211. const featureRefInfo = {
  1212. source,
  1213. featureIndex: -1,
  1214. };
  1215. switch (type) {
  1216. case "Point":
  1217. // 点
  1218. this.addPoint(coordinates, featureProperties, featureRefInfo);
  1219. break;
  1220. case "LineString":
  1221. // 线
  1222. this.addLine(coordinates, featureProperties, featureRefInfo);
  1223. break;
  1224. case "Polygon":
  1225. case "MultiPolygon":
  1226. // 面
  1227. this.addPolygon(coordinates, featureProperties, featureRefInfo);
  1228. break;
  1229. default:
  1230. break;
  1231. }
  1232. } else if (geojson.features) {
  1233. const features = geojson.features;
  1234. // 2. 遍历features,根据type添加到地图中
  1235. console.log("features", features);
  1236. features.forEach((feature, featureIndex) => {
  1237. const { type, coordinates } = feature.geometry;
  1238. const featureProperties = feature.properties || {};
  1239. const featureRefInfo = {
  1240. source,
  1241. featureIndex,
  1242. };
  1243. switch (type) {
  1244. case "Point":
  1245. // 点
  1246. this.addPoint(coordinates, featureProperties, featureRefInfo);
  1247. break;
  1248. case "LineString":
  1249. // 线
  1250. this.addLine(coordinates, featureProperties, featureRefInfo);
  1251. break;
  1252. case "Polygon":
  1253. case "MultiPolygon":
  1254. // 面
  1255. this.addPolygon(coordinates, featureProperties, featureRefInfo);
  1256. break;
  1257. default:
  1258. break;
  1259. }
  1260. });
  1261. }
  1262. setTimeout(() => {
  1263. viewer.scene.requestRender();
  1264. });
  1265. },
  1266. // 添加点到地图中
  1267. addPoint(coordinates, featureProperties = null, featureRefInfo = null) {
  1268. // 1. 解析点的坐标
  1269. console.log("addPoint coordinates", coordinates);
  1270. // 2. 创建点实体
  1271. const pointEntity = viewer.entities.add({
  1272. name: "point",
  1273. position:
  1274. coordinates.length > 2
  1275. ? SkyScenery.Cartesian3.fromDegrees(coordinates[0], coordinates[1], coordinates[2])
  1276. : SkyScenery.Cartesian3.fromDegrees(coordinates[0], coordinates[1]),
  1277. point: {
  1278. show: true,
  1279. color: SkyScenery.Color.RED,
  1280. pixelSize: 10,
  1281. outlineColor: SkyScenery.Color.WHITE,
  1282. outlineWidth: 2,
  1283. },
  1284. });
  1285. pointEntity.__featureProperties = featureProperties;
  1286. pointEntity.__featureRef = featureRefInfo;
  1287. // 3. 将点实体添加到drawnEntities中
  1288. this.drawnEntities.push(pointEntity);
  1289. },
  1290. // 添加线到地图中
  1291. addLine(coordinates, featureProperties = null, featureRefInfo = null) {
  1292. // 1. 解析线的坐标
  1293. console.log("addLine coordinates", coordinates);
  1294. // 2. 处理坐标格式:如果是二维数组则取第一个元素,否则直接使用
  1295. const lineCoordinates =
  1296. Array.isArray(coordinates[0]) && Array.isArray(coordinates[0][0])
  1297. ? coordinates[0]
  1298. : coordinates;
  1299. // 3. 检测坐标是否包含Z值
  1300. const hasZValues = lineCoordinates.some(
  1301. (coord) => coord.length > 2 && typeof coord[2] === "number"
  1302. );
  1303. // 4. 根据是否有Z值选择合适的坐标转换方法
  1304. let positions;
  1305. if (hasZValues) {
  1306. // 包含Z值,使用带高度的坐标转换方法
  1307. const flatCoordinatesWithHeights = [];
  1308. lineCoordinates.forEach((coord) => {
  1309. flatCoordinatesWithHeights.push(coord[0], coord[1], coord[2] || 0);
  1310. });
  1311. positions = SkyScenery.Cartesian3.fromDegreesArrayHeights(flatCoordinatesWithHeights);
  1312. } else {
  1313. // 不包含Z值,使用普通坐标转换方法
  1314. const flatCoordinates = [];
  1315. lineCoordinates.forEach((coord) => {
  1316. flatCoordinates.push(coord[0], coord[1]);
  1317. });
  1318. positions = SkyScenery.Cartesian3.fromDegreesArray(flatCoordinates);
  1319. }
  1320. // 5. 创建线实体
  1321. const lineEntity = viewer.entities.add({
  1322. name: "line",
  1323. polyline: {
  1324. show: true,
  1325. positions: positions,
  1326. material: SkyScenery.Color.BLUE.withAlpha(0.8),
  1327. width: 3,
  1328. },
  1329. });
  1330. lineEntity.__featureProperties = featureProperties;
  1331. lineEntity.__featureRef = featureRefInfo;
  1332. // 6. 将线实体添加到drawnEntities中
  1333. this.drawnEntities.push(lineEntity);
  1334. },
  1335. // 添加面到地图中
  1336. addPolygon(coordinates, featureProperties = null, featureRefInfo = null) {
  1337. // 检测是否为MultiPolygon类型(MultiPolygon的坐标是三维数组)
  1338. if (
  1339. Array.isArray(coordinates[0]) &&
  1340. Array.isArray(coordinates[0][0]) &&
  1341. Array.isArray(coordinates[0][0][0])
  1342. ) {
  1343. console.log("MultiPolygon coordinates", coordinates);
  1344. // 是MultiPolygon类型,遍历每个Polygon
  1345. coordinates.forEach((polygonCoordinates) => {
  1346. this.renderSinglePolygon(polygonCoordinates, featureProperties, featureRefInfo);
  1347. });
  1348. } else {
  1349. // 是单个Polygon类型
  1350. this.renderSinglePolygon(coordinates, featureProperties, featureRefInfo);
  1351. }
  1352. },
  1353. // 渲染单个Polygon
  1354. renderSinglePolygon(coordinates, featureProperties = null, featureRefInfo = null) {
  1355. // 1. 处理坐标格式:确保获取外部环坐标
  1356. const outerRingCoordinates =
  1357. Array.isArray(coordinates[0]) && Array.isArray(coordinates[0][0])
  1358. ? coordinates[0]
  1359. : coordinates;
  1360. // 2. 检测坐标是否包含Z值
  1361. const hasZValues = outerRingCoordinates.some(
  1362. (coord) => coord.length > 2 && typeof coord[2] === "number"
  1363. );
  1364. // 3. 根据是否有Z值选择合适的坐标转换方法
  1365. let positions;
  1366. let baseHeight = 0;
  1367. let extrudedHeight = 0; // 默认挤压高度
  1368. if (hasZValues) {
  1369. // 包含Z值,使用带高度的坐标转换方法
  1370. const flatCoordinatesWithHeights = [];
  1371. let minZ = Infinity;
  1372. let maxZ = -Infinity;
  1373. // 计算Z值的范围
  1374. outerRingCoordinates.forEach((coord) => {
  1375. const z = coord[2] || 0;
  1376. minZ = Math.min(minZ, z);
  1377. maxZ = Math.max(maxZ, z);
  1378. flatCoordinatesWithHeights.push(coord[0], coord[1], minZ); // 使用最小Z值作为基础高度
  1379. });
  1380. positions = SkyScenery.Cartesian3.fromDegreesArrayHeights(flatCoordinatesWithHeights);
  1381. baseHeight = minZ;
  1382. extrudedHeight = maxZ;
  1383. } else {
  1384. // 不包含Z值,使用普通坐标转换方法
  1385. const flatCoordinates = [];
  1386. outerRingCoordinates.forEach((coord) => {
  1387. flatCoordinates.push(coord[0], coord[1]);
  1388. });
  1389. positions = SkyScenery.Cartesian3.fromDegreesArray(flatCoordinates);
  1390. }
  1391. // 4. 创建面实体
  1392. const polygonEntity = viewer.entities.add({
  1393. name: "polygon",
  1394. polygon: {
  1395. hierarchy: {
  1396. positions: positions,
  1397. },
  1398. height: baseHeight, // 多边形底部高度
  1399. extrudedHeight: extrudedHeight, // 多边形顶部高度,实现3D挤压效果
  1400. heightReference: hasZValues
  1401. ? SkyScenery.HeightReference.NONE
  1402. : SkyScenery.HeightReference.CLAMP_TO_GROUND,
  1403. material: SkyScenery.Color.GREEN.withAlpha(0.5),
  1404. outline: true,
  1405. outlineColor: SkyScenery.Color.WHITE,
  1406. outlineWidth: 2,
  1407. // 设置侧面材质
  1408. extrudedMaterial: SkyScenery.Color.GREEN.withAlpha(0.8),
  1409. },
  1410. });
  1411. polygonEntity.__featureProperties = featureProperties;
  1412. polygonEntity.__featureRef = featureRefInfo;
  1413. // 5. 将面实体添加到drawnEntities中
  1414. this.drawnEntities.push(polygonEntity);
  1415. },
  1416. handleSelectChange(item, value) {
  1417. this.jsonData[item] = value;
  1418. },
  1419. // 复制json数据
  1420. copyJsonData(data) {
  1421. let textarea = document.createElement("textarea");
  1422. try {
  1423. textarea.value = JSON.stringify(data, null, 2);
  1424. document.body.appendChild(textarea);
  1425. // 3. 选中文本(兼容移动端)
  1426. textarea.select();
  1427. // 兼容移动端:设置选择范围覆盖全部文本
  1428. textarea.setSelectionRange(0, textarea.value.length);
  1429. // 4. 执行复制命令
  1430. const isSuccess = document.execCommand("copy");
  1431. if (isSuccess) {
  1432. this.$message({
  1433. message: "复制成功",
  1434. type: "success",
  1435. });
  1436. }
  1437. } catch (err) {
  1438. this.$message({
  1439. message: err,
  1440. type: "error",
  1441. });
  1442. } finally {
  1443. document.body.removeChild(textarea);
  1444. }
  1445. },
  1446. handleExceed(file) {
  1447. this.$message({
  1448. message: "最多只能上传一个文件",
  1449. type: "warning",
  1450. });
  1451. },
  1452. /** 时空格式转换等场景:上传文件仅允许 geojson / csv / xlsx / zip */
  1453. isAllowedSceneUploadFile(file) {
  1454. const name = (file && file.name) || (file.raw && file.raw.name) || "";
  1455. const lower = String(name).toLowerCase();
  1456. return (
  1457. lower.endsWith(".geojson") ||
  1458. lower.endsWith(".csv") ||
  1459. lower.endsWith(".xlsx") ||
  1460. lower.endsWith(".zip")
  1461. );
  1462. },
  1463. handleFileChange(file, fileList) {
  1464. if (!this.isAllowedSceneUploadFile(file)) {
  1465. this.$message.error("仅支持上传 .geojson、.csv、.xlsx、.zip 格式的文件,请重新选择");
  1466. this.currentFile = null;
  1467. this.fileList = [];
  1468. this.$nextTick(() => {
  1469. if (this.$refs.sceneFileUpload && this.$refs.sceneFileUpload.clearFiles) {
  1470. this.$refs.sceneFileUpload.clearFiles();
  1471. }
  1472. });
  1473. return;
  1474. }
  1475. this.currentFile = file;
  1476. this.refreshImportColumnOptions(file);
  1477. },
  1478. uploadRemove() {
  1479. this.currentFile = null;
  1480. this.params.geocodeColumnKeyword = "";
  1481. this.selectOptions.geocodeColumnKeyword = [];
  1482. },
  1483. parseCsvHeaderLine(line) {
  1484. const out = [];
  1485. let cur = "";
  1486. let inq = false;
  1487. for (let i = 0; i < line.length; i++) {
  1488. const c = line[i];
  1489. if (c === '"') {
  1490. inq = !inq;
  1491. continue;
  1492. }
  1493. if (!inq && c === ",") {
  1494. out.push(cur.trim());
  1495. cur = "";
  1496. continue;
  1497. }
  1498. cur += c;
  1499. }
  1500. out.push(cur.trim());
  1501. return out.filter((h) => h.length > 0);
  1502. },
  1503. async refreshImportColumnOptions(file) {
  1504. this.params.geocodeColumnKeyword = "";
  1505. this.selectOptions.geocodeColumnKeyword = [];
  1506. const raw = file && (file.raw || file);
  1507. if (!raw || !raw.name) {
  1508. return;
  1509. }
  1510. const name = String(raw.name).toLowerCase();
  1511. if (name.endsWith(".zip")) {
  1512. this.$message.info("zip 包请在列名输入框中填写与各 xlsx 表头一致的列名");
  1513. return;
  1514. }
  1515. try {
  1516. if (name.endsWith(".csv")) {
  1517. const text = await raw.text();
  1518. const firstLine = (text.split(/\r?\n/).find((l) => l.trim().length > 0) || "").trim();
  1519. if (!firstLine) {
  1520. return;
  1521. }
  1522. const headers = this.parseCsvHeaderLine(firstLine);
  1523. this.selectOptions.geocodeColumnKeyword = headers.map((h) => ({
  1524. value: h,
  1525. label: h,
  1526. }));
  1527. this.$message.success("已解析 CSV 表头,共 " + headers.length + " 列");
  1528. } else if (name.endsWith(".xlsx") || name.endsWith(".xls")) {
  1529. const buf = await raw.arrayBuffer();
  1530. const wb = XLSX.read(buf, { type: "array" });
  1531. const sheetName = wb.SheetNames[0];
  1532. const sheet = wb.Sheets[sheetName];
  1533. const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: "" });
  1534. const headers = (rows[0] || []).map((c) => String(c).trim()).filter((c) => c.length > 0);
  1535. this.selectOptions.geocodeColumnKeyword = headers.map((h) => ({
  1536. value: h,
  1537. label: h,
  1538. }));
  1539. this.$message.success("已解析 Excel 首行表头,共 " + headers.length + " 列");
  1540. }
  1541. } catch (e) {
  1542. console.error(e);
  1543. this.$message.warning("解析表头失败,可手动在「列名」中输入与表格一致的列名");
  1544. }
  1545. },
  1546. handleChange(emit) {
  1547. this.params.unit = "";
  1548. this.params.keyType = "";
  1549. this.params.geocodeColumnKeyword = "";
  1550. this.selectOptions.geocodeColumnKeyword = [];
  1551. this.fileList = [];
  1552. this.currentFile = null;
  1553. // 清除所有地图中的元素
  1554. this.clearAll();
  1555. this.jsonData = {};
  1556. this.backData = {};
  1557. this.renderStatus = {
  1558. input: false,
  1559. output: false,
  1560. };
  1561. this.renderedGeojsonCache = {
  1562. input: null,
  1563. output: null,
  1564. };
  1565. this.currentRenderedSource = "";
  1566. this.propertyDialog.visible = false;
  1567. this.propertyDialog.list = [];
  1568. this.propertyDialog.source = "";
  1569. this.propertyDialog.propertiesRef = null;
  1570. this.propertyDialog.featureIndex = -1;
  1571. this.SceneValue = emit[emit.length - 1];
  1572. },
  1573. // 初始化绘制处理器
  1574. initDrawHandler() {
  1575. // 创建绘制处理器
  1576. if (!this.handler) {
  1577. this.handler = new SkyScenery.ScreenSpaceEventHandler(viewer.canvas);
  1578. }
  1579. this.initFeaturePickHandler();
  1580. },
  1581. resetPickDragState() {
  1582. this._pickDrag = null;
  1583. },
  1584. /** @param {boolean} exitEditMode 为 false 时仅清除选中与高亮,用于在「节点编辑」内切换要素 */
  1585. clearMapEditSelection(exitEditMode = true) {
  1586. this.removeVertexHandleEntities();
  1587. const prevEntity = this.mapEditSelection && this.mapEditSelection.entity;
  1588. this.mapEditSelection = null;
  1589. this.hoveredVertexIndex = -1;
  1590. this.hoveredHandleEntity = null;
  1591. this.clearHoveredFeatureStyle();
  1592. if (exitEditMode) {
  1593. this.geometryEditMode = false;
  1594. this.pickedFeatureRef = null;
  1595. }
  1596. this.hideHoverHint();
  1597. this.restoreEntityHighlight(prevEntity);
  1598. this.setScreenSpaceCameraForDrag(true);
  1599. if (viewer) {
  1600. viewer.scene.requestRender();
  1601. }
  1602. },
  1603. removeVertexHandleEntities() {
  1604. if (!viewer || !this.vertexHandleEntities.length) {
  1605. this.vertexHandleEntities = [];
  1606. return;
  1607. }
  1608. this.vertexHandleEntities.forEach((e) => {
  1609. try {
  1610. viewer.entities.remove(e);
  1611. } catch (err) {
  1612. /* ignore */
  1613. }
  1614. });
  1615. this.vertexHandleEntities = [];
  1616. },
  1617. restoreEntityHighlight(entIn) {
  1618. const ent = entIn || (this.mapEditSelection && this.mapEditSelection.entity);
  1619. if (!ent || !ent.__editBackup || !viewer) {
  1620. return;
  1621. }
  1622. const b = ent.__editBackup;
  1623. if (ent.point && b.point) {
  1624. ent.point.pixelSize = b.point.pixelSize;
  1625. ent.point.color = b.point.color;
  1626. ent.point.outlineColor = b.point.outlineColor;
  1627. ent.point.outlineWidth = b.point.outlineWidth;
  1628. }
  1629. if (ent.polyline && b.polyline) {
  1630. ent.polyline.width = b.polyline.width;
  1631. ent.polyline.material = b.polyline.material;
  1632. }
  1633. if (ent.polygon && b.polygon) {
  1634. if (b.polygon.material != null) {
  1635. ent.polygon.material = b.polygon.material;
  1636. }
  1637. if (b.polygon.outlineWidth != null) {
  1638. ent.polygon.outlineWidth = b.polygon.outlineWidth;
  1639. }
  1640. if (b.polygon.outlineColor != null) {
  1641. ent.polygon.outlineColor = b.polygon.outlineColor;
  1642. }
  1643. }
  1644. delete ent.__editBackup;
  1645. },
  1646. applyEntityHighlight(entity, geometryType) {
  1647. if (!entity || !viewer) {
  1648. return;
  1649. }
  1650. if (!entity.__editBackup) {
  1651. entity.__editBackup = {};
  1652. if (entity.point) {
  1653. const p = entity.point;
  1654. entity.__editBackup.point = {
  1655. pixelSize: p.pixelSize,
  1656. color: p.color,
  1657. outlineColor: p.outlineColor,
  1658. outlineWidth: p.outlineWidth,
  1659. };
  1660. }
  1661. if (entity.polyline) {
  1662. const pl = entity.polyline;
  1663. entity.__editBackup.polyline = {
  1664. width: pl.width,
  1665. material: pl.material,
  1666. };
  1667. }
  1668. if (entity.polygon) {
  1669. const pg = entity.polygon;
  1670. entity.__editBackup.polygon = {
  1671. material: pg.material,
  1672. outlineWidth: pg.outlineWidth,
  1673. outlineColor: pg.outlineColor,
  1674. };
  1675. }
  1676. }
  1677. const C = SkyScenery.Color;
  1678. if (geometryType === "Point" && entity.point) {
  1679. entity.point.pixelSize = 16;
  1680. entity.point.color = C.YELLOW.withAlpha(0.95);
  1681. entity.point.outlineColor = C.DEEPSKYBLUE;
  1682. entity.point.outlineWidth = 3;
  1683. } else if (geometryType === "LineString" && entity.polyline) {
  1684. entity.polyline.width = 6;
  1685. entity.polyline.material = C.CYAN.withAlpha(0.95);
  1686. } else if (geometryType === "Polygon" && entity.polygon) {
  1687. entity.polygon.outlineWidth = 4;
  1688. entity.polygon.outlineColor = C.CYAN;
  1689. entity.polygon.material = C.LIME.withAlpha(0.45);
  1690. }
  1691. },
  1692. getVertexHandleStyle(mode, handleType = "vertex") {
  1693. const C = SkyScenery.Color;
  1694. if (handleType === "midpoint") {
  1695. if (mode === "pressed") {
  1696. return {
  1697. pixelSize: 12,
  1698. color: C.ORANGE,
  1699. outlineColor: C.WHITE,
  1700. outlineWidth: 3,
  1701. };
  1702. }
  1703. if (mode === "hover") {
  1704. return {
  1705. pixelSize: 10,
  1706. color: C.YELLOW,
  1707. outlineColor: C.DARKBLUE,
  1708. outlineWidth: 2,
  1709. };
  1710. }
  1711. return {
  1712. pixelSize: 7,
  1713. color: C.RED.withAlpha(0.9),
  1714. outlineColor: C.WHITE,
  1715. outlineWidth: 1,
  1716. };
  1717. }
  1718. if (mode === "pressed") {
  1719. return {
  1720. pixelSize: 15,
  1721. color: C.ORANGE,
  1722. outlineColor: C.WHITE,
  1723. outlineWidth: 3,
  1724. };
  1725. }
  1726. if (mode === "hover") {
  1727. return {
  1728. pixelSize: 12,
  1729. color: C.YELLOW,
  1730. outlineColor: C.DARKBLUE,
  1731. outlineWidth: 2,
  1732. };
  1733. }
  1734. return {
  1735. pixelSize: 9,
  1736. color: C.WHITE,
  1737. outlineColor: C.DEEPSKYBLUE,
  1738. outlineWidth: 2,
  1739. };
  1740. },
  1741. applyVertexHandleStyles() {
  1742. if (!this.vertexHandleEntities.length) {
  1743. return;
  1744. }
  1745. const dragging = this._pickDrag && this._pickDrag.dragging;
  1746. const dragHandle = dragging ? this._pickDrag.dragHandleEntity || null : null;
  1747. this.vertexHandleEntities.forEach((h) => {
  1748. if (!h || !h.point) {
  1749. return;
  1750. }
  1751. let mode = "default";
  1752. if (dragging && dragHandle && h === dragHandle) {
  1753. mode = "pressed";
  1754. } else if (this.hoveredHandleEntity && h === this.hoveredHandleEntity) {
  1755. mode = "hover";
  1756. }
  1757. const s = this.getVertexHandleStyle(mode, h.__handleType || "vertex");
  1758. h.point.pixelSize = s.pixelSize;
  1759. h.point.color = s.color;
  1760. h.point.outlineColor = s.outlineColor;
  1761. h.point.outlineWidth = s.outlineWidth;
  1762. });
  1763. },
  1764. applyPointSelectionVisualByHoverPress() {
  1765. const sel = this.mapEditSelection;
  1766. if (!sel || sel.geometryType !== "Point" || !sel.entity || !sel.entity.point) {
  1767. return;
  1768. }
  1769. const ent = sel.entity;
  1770. const dragging = this._pickDrag && this._pickDrag.dragging && this._pickDrag.geometryType === "Point";
  1771. const C = SkyScenery.Color;
  1772. if (dragging) {
  1773. ent.point.pixelSize = 18;
  1774. ent.point.color = C.ORANGE.withAlpha(0.98);
  1775. ent.point.outlineColor = C.WHITE;
  1776. ent.point.outlineWidth = 4;
  1777. } else if (this.hoveredVertexIndex === 0) {
  1778. ent.point.pixelSize = 17;
  1779. ent.point.color = C.LIME.withAlpha(0.95);
  1780. ent.point.outlineColor = C.DEEPSKYBLUE;
  1781. ent.point.outlineWidth = 3;
  1782. } else {
  1783. this.applyEntityHighlight(ent, "Point");
  1784. }
  1785. },
  1786. refreshVertexHandlesFromPositions(positions) {
  1787. if (!positions || !this.vertexHandleEntities.length) {
  1788. return;
  1789. }
  1790. this.vertexHandleEntities.forEach((h) => {
  1791. const i = h.__vertexIndex;
  1792. if (h.__handleType === "vertex" && i >= 0 && i < positions.length) {
  1793. h.position = SkyScenery.Cartesian3.clone(positions[i], new SkyScenery.Cartesian3());
  1794. } else if (h.__handleType === "midpoint") {
  1795. const a = h.__insertAfter;
  1796. const b = a + 1;
  1797. if (a >= 0 && b < positions.length) {
  1798. h.position = SkyScenery.Cartesian3.midpoint(
  1799. positions[a],
  1800. positions[b],
  1801. new SkyScenery.Cartesian3()
  1802. );
  1803. }
  1804. }
  1805. });
  1806. if (viewer) {
  1807. viewer.scene.requestRender();
  1808. }
  1809. },
  1810. hideHoverHint() {
  1811. this.hoverHint.visible = false;
  1812. this.hoverHint.text = "";
  1813. },
  1814. clearHoveredFeatureStyle() {
  1815. const ent = this.hoveredFeatureEntity;
  1816. if (!ent || !ent.__hoverBackup) {
  1817. this.hoveredFeatureEntity = null;
  1818. return;
  1819. }
  1820. const b = ent.__hoverBackup;
  1821. if (ent.point && b.point) {
  1822. ent.point.pixelSize = b.point.pixelSize;
  1823. ent.point.color = b.point.color;
  1824. ent.point.outlineColor = b.point.outlineColor;
  1825. }
  1826. if (ent.polyline && b.polyline) {
  1827. ent.polyline.width = b.polyline.width;
  1828. ent.polyline.material = b.polyline.material;
  1829. }
  1830. if (ent.polygon && b.polygon) {
  1831. ent.polygon.outlineWidth = b.polygon.outlineWidth;
  1832. ent.polygon.outlineColor = b.polygon.outlineColor;
  1833. }
  1834. delete ent.__hoverBackup;
  1835. this.hoveredFeatureEntity = null;
  1836. },
  1837. applyHoveredFeatureStyle(entity) {
  1838. if (!entity || (this.mapEditSelection && this.mapEditSelection.entity === entity)) {
  1839. this.clearHoveredFeatureStyle();
  1840. return;
  1841. }
  1842. if (this.hoveredFeatureEntity === entity) {
  1843. return;
  1844. }
  1845. this.clearHoveredFeatureStyle();
  1846. entity.__hoverBackup = {};
  1847. const C = SkyScenery.Color;
  1848. if (entity.point) {
  1849. entity.__hoverBackup.point = {
  1850. pixelSize: entity.point.pixelSize,
  1851. color: entity.point.color,
  1852. outlineColor: entity.point.outlineColor,
  1853. };
  1854. entity.point.pixelSize = 13;
  1855. entity.point.color = C.CYAN.withAlpha(0.95);
  1856. entity.point.outlineColor = C.WHITE;
  1857. } else if (entity.polyline) {
  1858. entity.__hoverBackup.polyline = {
  1859. width: entity.polyline.width,
  1860. material: entity.polyline.material,
  1861. };
  1862. entity.polyline.width = 5;
  1863. entity.polyline.material = C.CYAN.withAlpha(0.92);
  1864. } else if (entity.polygon) {
  1865. entity.__hoverBackup.polygon = {
  1866. outlineWidth: entity.polygon.outlineWidth,
  1867. outlineColor: entity.polygon.outlineColor,
  1868. };
  1869. entity.polygon.outlineWidth = 3;
  1870. entity.polygon.outlineColor = C.CYAN;
  1871. }
  1872. this.hoveredFeatureEntity = entity;
  1873. },
  1874. findNearestHandleByScreen(screenPosition, maxDistPx = 18) {
  1875. if (!this.vertexHandleEntities || !this.vertexHandleEntities.length) {
  1876. return null;
  1877. }
  1878. let best = null;
  1879. let bestD = maxDistPx;
  1880. this.vertexHandleEntities.forEach((h) => {
  1881. if (!h || !h.position) return;
  1882. const p = h.position.getValue ? h.position.getValue(viewer.clock.currentTime) : h.position;
  1883. const d = this.screenDistanceToCartesian(screenPosition, p);
  1884. if (d < bestD) {
  1885. bestD = d;
  1886. best = h;
  1887. }
  1888. });
  1889. return best;
  1890. },
  1891. showHoverHint(screenPosition, text) {
  1892. if (!screenPosition || !text) {
  1893. this.hideHoverHint();
  1894. return;
  1895. }
  1896. this.hoverHint.visible = true;
  1897. this.hoverHint.text = text;
  1898. this.hoverHint.left = screenPosition.x + 14;
  1899. this.hoverHint.top = screenPosition.y + 16;
  1900. },
  1901. createVertexHandlesForSelection(entity, geometryType, positionsArray) {
  1902. this.removeVertexHandleEntities();
  1903. if (!viewer || !entity || !positionsArray || !positionsArray.length) {
  1904. return;
  1905. }
  1906. const featureRef = entity.__featureRef;
  1907. const C = SkyScenery.Color;
  1908. let indices = positionsArray.map((_, i) => i);
  1909. const n = positionsArray.length;
  1910. if (
  1911. geometryType === "Polygon" &&
  1912. n > 2 &&
  1913. SkyScenery.Cartesian3.distance(positionsArray[0], positionsArray[n - 1]) < 0.5
  1914. ) {
  1915. indices = indices.slice(0, -1);
  1916. }
  1917. indices.forEach((vertexIndex) => {
  1918. const pos = positionsArray[vertexIndex];
  1919. const h = viewer.entities.add({
  1920. position: SkyScenery.Cartesian3.clone(pos, new SkyScenery.Cartesian3()),
  1921. point: {
  1922. show: true,
  1923. color: C.WHITE,
  1924. pixelSize: 9,
  1925. outlineColor: C.DEEPSKYBLUE,
  1926. outlineWidth: 2,
  1927. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  1928. },
  1929. });
  1930. h.__vertexHandle = true;
  1931. h.__handleType = "vertex";
  1932. h.__vertexIndex = vertexIndex;
  1933. h.__parentEntity = entity;
  1934. h.__featureRef = featureRef;
  1935. this.vertexHandleEntities.push(h);
  1936. });
  1937. // 在相邻顶点中间增加可插入顶点的中点柄
  1938. const segCount = geometryType === "Polygon" ? indices.length : Math.max(0, indices.length - 1);
  1939. for (let i = 0; i < segCount; i++) {
  1940. const aIdx = indices[i];
  1941. const bIdx = geometryType === "Polygon" ? indices[(i + 1) % indices.length] : indices[i + 1];
  1942. if (aIdx == null || bIdx == null) continue;
  1943. const a = positionsArray[aIdx];
  1944. const b = positionsArray[bIdx];
  1945. if (!a || !b) continue;
  1946. const mid = SkyScenery.Cartesian3.midpoint(a, b, new SkyScenery.Cartesian3());
  1947. const m = viewer.entities.add({
  1948. position: mid,
  1949. point: {
  1950. show: true,
  1951. color: C.RED.withAlpha(0.9),
  1952. pixelSize: 7,
  1953. outlineColor: C.WHITE,
  1954. outlineWidth: 1,
  1955. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  1956. },
  1957. });
  1958. m.__vertexHandle = true;
  1959. m.__handleType = "midpoint";
  1960. m.__insertAfter = aIdx;
  1961. m.__vertexIndex = -1;
  1962. m.__parentEntity = entity;
  1963. m.__featureRef = featureRef;
  1964. this.vertexHandleEntities.push(m);
  1965. }
  1966. this.applyVertexHandleStyles();
  1967. },
  1968. applyMapEditSelection(entity) {
  1969. if (!this.geometryEditMode) {
  1970. return;
  1971. }
  1972. if (!entity || !viewer || !entity.__featureRef) {
  1973. return;
  1974. }
  1975. const g =
  1976. this.getSourceGeojsonData(entity.__featureRef.source || "input") ||
  1977. this.renderedGeojsonCache[entity.__featureRef.source];
  1978. const fi = entity.__featureRef.featureIndex;
  1979. if (!g || !g.features || fi < 0 || !g.features[fi] || !g.features[fi].geometry) {
  1980. return;
  1981. }
  1982. const geom = g.features[fi].geometry;
  1983. const gt = geom.type === "MultiPolygon" ? null : geom.type;
  1984. if (!gt || gt === "MultiPolygon") {
  1985. return;
  1986. }
  1987. if (this.mapEditSelection && this.mapEditSelection.entity === entity) {
  1988. const now = viewer.clock.currentTime;
  1989. const gType = this.mapEditSelection.geometryType;
  1990. this.removeVertexHandleEntities();
  1991. if (gType === "LineString" && entity.polyline && entity.polyline.positions) {
  1992. const arr = entity.polyline.positions.getValue(now);
  1993. if (arr && arr.length) {
  1994. this.createVertexHandlesForSelection(entity, "LineString", arr);
  1995. }
  1996. } else if (gType === "Polygon" && entity.polygon && entity.polygon.hierarchy) {
  1997. const hProp = entity.polygon.hierarchy;
  1998. const hier =
  1999. hProp && typeof hProp.getValue === "function" ? hProp.getValue(now) : hProp;
  2000. const arr = hier && hier.positions;
  2001. if (arr && arr.length) {
  2002. this.createVertexHandlesForSelection(entity, "Polygon", arr);
  2003. }
  2004. }
  2005. this.applyVertexHandleStyles();
  2006. this.applyPointSelectionVisualByHoverPress();
  2007. return;
  2008. }
  2009. this.clearMapEditSelection(false);
  2010. this.mapEditSelection = {
  2011. entity,
  2012. geometryType: gt,
  2013. source: entity.__featureRef.source || "input",
  2014. featureIndex: fi,
  2015. };
  2016. this.applyEntityHighlight(entity, gt === "LineString" ? "LineString" : gt === "Polygon" ? "Polygon" : "Point");
  2017. const now = viewer.clock.currentTime;
  2018. if (gt === "LineString" && entity.polyline && entity.polyline.positions) {
  2019. const arr = entity.polyline.positions.getValue(now);
  2020. if (arr && arr.length) {
  2021. this.createVertexHandlesForSelection(entity, "LineString", arr);
  2022. }
  2023. } else if (gt === "Polygon" && entity.polygon && entity.polygon.hierarchy) {
  2024. const hProp = entity.polygon.hierarchy;
  2025. const hier = hProp && typeof hProp.getValue === "function" ? hProp.getValue(now) : hProp;
  2026. const arr = hier && hier.positions;
  2027. if (arr && arr.length) {
  2028. this.createVertexHandlesForSelection(entity, "Polygon", arr);
  2029. }
  2030. }
  2031. this.hoveredVertexIndex = -1;
  2032. this.applyVertexHandleStyles();
  2033. this.applyPointSelectionVisualByHoverPress();
  2034. viewer.scene.requestRender();
  2035. },
  2036. updateVertexHoverFromPick(screenPosition, precomputedNearHandle = null) {
  2037. if (!this.mapEditSelection || !this.mapEditSelection.entity) {
  2038. this.hoveredVertexIndex = -1;
  2039. this.hoveredHandleEntity = null;
  2040. this.hideHoverHint();
  2041. return;
  2042. }
  2043. if (this._pickDrag && this._pickDrag.dragging) {
  2044. this.hoveredVertexIndex = this._pickDrag.vertexIndex;
  2045. this.hoveredHandleEntity = this._pickDrag.dragHandleEntity || null;
  2046. this.applyVertexHandleStyles();
  2047. this.applyPointSelectionVisualByHoverPress();
  2048. this.showHoverHint(screenPosition, "可拖拽调整节点位置");
  2049. return;
  2050. }
  2051. // 与按下逻辑一致:优先按屏幕距离命中顶点/中点柄。纯 pick 常会先拾取到面/线填充而非小点实体。
  2052. let e =
  2053. precomputedNearHandle ||
  2054. (this.vertexHandleEntities && this.vertexHandleEntities.length
  2055. ? this.findNearestHandleByScreen(screenPosition, 32)
  2056. : null);
  2057. if (!e) {
  2058. const pickedObject = viewer.scene.pick(screenPosition);
  2059. e = pickedObject && pickedObject.id && pickedObject.id.__vertexHandle ? pickedObject.id : null;
  2060. }
  2061. if (e && e.__vertexHandle) {
  2062. this.hoveredHandleEntity = e;
  2063. this.hoveredVertexIndex = typeof e.__vertexIndex === "number" ? e.__vertexIndex : -1;
  2064. if (e.__handleType === "midpoint") {
  2065. this.showHoverHint(screenPosition, "拖动可新增节点");
  2066. } else {
  2067. this.showHoverHint(screenPosition, "可拖拽调整节点位置");
  2068. }
  2069. } else if (this.mapEditSelection.geometryType === "Point") {
  2070. const pickedPoint = viewer.scene.pick(screenPosition);
  2071. const pe = pickedPoint && pickedPoint.id;
  2072. if (pe === this.mapEditSelection.entity) {
  2073. this.hoveredVertexIndex = 0;
  2074. this.hoveredHandleEntity = null;
  2075. this.showHoverHint(screenPosition, "可拖拽调整节点位置");
  2076. } else {
  2077. this.hoveredVertexIndex = -1;
  2078. this.hoveredHandleEntity = null;
  2079. this.hideHoverHint();
  2080. }
  2081. } else {
  2082. this.hoveredVertexIndex = -1;
  2083. this.hoveredHandleEntity = null;
  2084. this.hideHoverHint();
  2085. }
  2086. this.applyVertexHandleStyles();
  2087. this.applyPointSelectionVisualByHoverPress();
  2088. if (viewer) {
  2089. viewer.scene.requestRender();
  2090. }
  2091. },
  2092. setScreenSpaceCameraForDrag(enable) {
  2093. if (!viewer || !viewer.scene || !viewer.scene.screenSpaceCameraController) {
  2094. return;
  2095. }
  2096. const c = viewer.scene.screenSpaceCameraController;
  2097. c.enableInputs = enable;
  2098. c.enableRotate = enable;
  2099. c.enableTranslate = enable;
  2100. c.enableZoom = enable;
  2101. c.enableTilt = enable;
  2102. c.enableLook = enable;
  2103. },
  2104. /** 拖动顶点/线/面或折线面绘制时启用连续渲染,结束后恢复 Example 中的 requestRenderMode */
  2105. enterInteractiveSceneRender() {
  2106. if (!viewer || !viewer.scene) {
  2107. return;
  2108. }
  2109. if (this._interactiveRenderDepth === 0) {
  2110. this._savedSceneRenderMode = {
  2111. requestRenderMode: viewer.scene.requestRenderMode,
  2112. maximumRenderTimeChange: viewer.scene.maximumRenderTimeChange,
  2113. };
  2114. viewer.scene.requestRenderMode = false;
  2115. viewer.scene.maximumRenderTimeChange = 0;
  2116. }
  2117. this._interactiveRenderDepth++;
  2118. },
  2119. exitInteractiveSceneRender() {
  2120. if (!viewer || !viewer.scene || this._interactiveRenderDepth <= 0) {
  2121. return;
  2122. }
  2123. this._interactiveRenderDepth--;
  2124. if (this._interactiveRenderDepth === 0 && this._savedSceneRenderMode) {
  2125. viewer.scene.requestRenderMode = this._savedSceneRenderMode.requestRenderMode;
  2126. viewer.scene.maximumRenderTimeChange = this._savedSceneRenderMode.maximumRenderTimeChange;
  2127. this._savedSceneRenderMode = null;
  2128. }
  2129. },
  2130. /** globe.pick 在快速移动时易失败;补充 pickPosition / 椭球拾取,保证几何与柄同步 */
  2131. pickSurfaceCartesian(screenPosition) {
  2132. if (!viewer || !viewer.scene || !viewer.camera || !screenPosition) {
  2133. return null;
  2134. }
  2135. const ray = viewer.camera.getPickRay(screenPosition);
  2136. if (!ray) {
  2137. return null;
  2138. }
  2139. let cart = viewer.scene.globe.pick(ray, viewer.scene);
  2140. if (cart) {
  2141. return cart;
  2142. }
  2143. if (typeof viewer.scene.pickPosition === "function") {
  2144. cart = viewer.scene.pickPosition(screenPosition);
  2145. if (cart) {
  2146. return cart;
  2147. }
  2148. }
  2149. const ellipsoid = viewer.scene.globe && viewer.scene.globe.ellipsoid;
  2150. if (ellipsoid && typeof viewer.camera.pickEllipsoid === "function") {
  2151. return viewer.camera.pickEllipsoid(screenPosition, ellipsoid);
  2152. }
  2153. return null;
  2154. },
  2155. wgs84PointToScreen(cartesian) {
  2156. if (!viewer || !cartesian) {
  2157. return null;
  2158. }
  2159. const ST = SkyScenery.SceneTransforms;
  2160. if (!ST || typeof ST.wgs84ToWindowCoordinates !== "function") {
  2161. return null;
  2162. }
  2163. const win = new SkyScenery.Cartesian2();
  2164. if (!ST.wgs84ToWindowCoordinates(viewer.scene, cartesian, win)) {
  2165. return null;
  2166. }
  2167. return win;
  2168. },
  2169. screenDistanceToCartesian(screenPos, cartesian) {
  2170. const win = this.wgs84PointToScreen(cartesian);
  2171. if (!win) {
  2172. return Infinity;
  2173. }
  2174. const dx = win.x - screenPos.x;
  2175. const dy = win.y - screenPos.y;
  2176. return Math.sqrt(dx * dx + dy * dy);
  2177. },
  2178. findClosestVertexIndexScreen(positions, screenPos, maxDistPx) {
  2179. if (!positions || !positions.length) {
  2180. return -1;
  2181. }
  2182. let best = -1;
  2183. let bestD = maxDistPx;
  2184. for (let i = 0; i < positions.length; i++) {
  2185. const d = this.screenDistanceToCartesian(screenPos, positions[i]);
  2186. if (d < bestD) {
  2187. bestD = d;
  2188. best = i;
  2189. }
  2190. }
  2191. return best;
  2192. },
  2193. cloneCartesian3Array(arr) {
  2194. return arr.map((p) => SkyScenery.Cartesian3.clone(p, new SkyScenery.Cartesian3()));
  2195. },
  2196. openFeaturePropertyDialogForEntity(entity) {
  2197. const featureIndex =
  2198. entity.__featureRef && typeof entity.__featureRef.featureIndex === "number"
  2199. ? entity.__featureRef.featureIndex
  2200. : -1;
  2201. const propertySource =
  2202. (entity.__featureRef && entity.__featureRef.source) || this.currentRenderedSource || "input";
  2203. const geojsonData =
  2204. this.getSourceGeojsonData(propertySource) || this.renderedGeojsonCache[propertySource];
  2205. let propertiesRef = null;
  2206. if (geojsonData) {
  2207. if (
  2208. entity.__featureRef &&
  2209. typeof entity.__featureRef.featureIndex === "number" &&
  2210. entity.__featureRef.featureIndex >= 0 &&
  2211. geojsonData.features &&
  2212. geojsonData.features[entity.__featureRef.featureIndex]
  2213. ) {
  2214. if (!geojsonData.features[entity.__featureRef.featureIndex].properties) {
  2215. geojsonData.features[entity.__featureRef.featureIndex].properties = {};
  2216. }
  2217. propertiesRef = geojsonData.features[entity.__featureRef.featureIndex].properties;
  2218. } else {
  2219. if (!geojsonData.properties) {
  2220. geojsonData.properties = {};
  2221. }
  2222. propertiesRef = geojsonData.properties;
  2223. }
  2224. }
  2225. const propertyList = this.formatFeatureProperties(
  2226. propertiesRef || entity.__featureProperties || {}
  2227. );
  2228. if (
  2229. propertiesRef ||
  2230. (entity.__featureProperties && typeof entity.__featureProperties === "object")
  2231. ) {
  2232. this.pickedFeatureRef = {
  2233. entity,
  2234. source: propertySource,
  2235. featureIndex,
  2236. };
  2237. this.propertyDialog.source = propertySource;
  2238. this.propertyDialog.propertiesRef = propertiesRef || entity.__featureProperties || {};
  2239. this.propertyDialog.featureIndex = featureIndex;
  2240. this.propertyDialog.list = propertyList;
  2241. this.propertyDialog.visible = true;
  2242. } else {
  2243. this.pickedFeatureRef = {
  2244. entity,
  2245. source: propertySource,
  2246. featureIndex,
  2247. };
  2248. this.propertyDialog.visible = false;
  2249. this.propertyDialog.list = [];
  2250. this.propertyDialog.source = "";
  2251. this.propertyDialog.propertiesRef = null;
  2252. this.propertyDialog.featureIndex = -1;
  2253. }
  2254. },
  2255. commitDraggedGeometryToGeojson(st) {
  2256. if (!st || !st.entity || st.featureIndex < 0) {
  2257. return;
  2258. }
  2259. const g = this.getSourceGeojsonData(st.source);
  2260. if (!g || !g.features || !g.features[st.featureIndex] || !g.features[st.featureIndex].geometry) {
  2261. return;
  2262. }
  2263. const geom = g.features[st.featureIndex].geometry;
  2264. const now = viewer.clock.currentTime;
  2265. const toLonLat = (c3, origCoord) => {
  2266. const c = SkyScenery.Cartographic.fromCartesian(c3);
  2267. const lon = SkyScenery.Math.toDegrees(c.longitude);
  2268. const lat = SkyScenery.Math.toDegrees(c.latitude);
  2269. if (origCoord && origCoord.length > 2 && typeof origCoord[2] === "number") {
  2270. return [lon, lat, origCoord[2]];
  2271. }
  2272. return [lon, lat];
  2273. };
  2274. if (geom.type === "Point" && st.entity.position) {
  2275. const p = st.entity.position.getValue(now);
  2276. if (!p) {
  2277. return;
  2278. }
  2279. const orig = geom.coordinates;
  2280. geom.coordinates = toLonLat(p, orig);
  2281. return;
  2282. }
  2283. if (geom.type === "LineString" && st.workingPositions) {
  2284. geom.coordinates = st.workingPositions.map((c3, i) => toLonLat(c3, geom.coordinates[i]));
  2285. return;
  2286. }
  2287. if (geom.type === "Polygon" && st.workingPositions) {
  2288. const ring = st.workingPositions.map((c3, i) => {
  2289. const origRing = (geom.coordinates && geom.coordinates[0]) || [];
  2290. return toLonLat(c3, origRing[i]);
  2291. });
  2292. if (ring.length > 1) {
  2293. const a = ring[0];
  2294. const b = ring[ring.length - 1];
  2295. if (a[0] !== b[0] || a[1] !== b[1] || (a[2] !== undefined && b[2] !== undefined && a[2] !== b[2])) {
  2296. ring.push([...a]);
  2297. }
  2298. }
  2299. if (!geom.coordinates) {
  2300. geom.coordinates = [];
  2301. }
  2302. geom.coordinates[0] = ring;
  2303. }
  2304. },
  2305. syncPolygonEntityHierarchy(entity, positions) {
  2306. if (!entity || !entity.polygon) {
  2307. return;
  2308. }
  2309. const n = positions.length;
  2310. if (n > 1) {
  2311. const a = positions[0];
  2312. const b = positions[n - 1];
  2313. if (SkyScenery.Cartesian3.distance(a, b) < 0.5) {
  2314. positions[n - 1] = SkyScenery.Cartesian3.clone(a, new SkyScenery.Cartesian3());
  2315. }
  2316. }
  2317. entity.polygon.hierarchy = new SkyScenery.PolygonHierarchy(this.cloneCartesian3Array(positions));
  2318. },
  2319. tryBeginPickDrag(event) {
  2320. if (this.currentTool || this.isDrawingHole) {
  2321. return;
  2322. }
  2323. const nearHandle = this.geometryEditMode ? this.findNearestHandleByScreen(event.position, 32) : null;
  2324. const pickedObject = nearHandle ? { id: nearHandle } : viewer.scene.pick(event.position);
  2325. if (!SkyScenery.defined(pickedObject) || !SkyScenery.defined(pickedObject.id)) {
  2326. this.propertyDialog.visible = false;
  2327. this.propertyDialog.list = [];
  2328. this.propertyDialog.source = "";
  2329. this.propertyDialog.propertiesRef = null;
  2330. this.propertyDialog.featureIndex = -1;
  2331. this.resetPickDragState();
  2332. this.clearMapEditSelection();
  2333. return;
  2334. }
  2335. const entity = pickedObject.id;
  2336. if (!this.geometryEditMode) {
  2337. if (!entity.__featureRef || typeof entity.__featureRef.featureIndex !== "number") {
  2338. this.resetPickDragState();
  2339. return;
  2340. }
  2341. this._pickDrag = {
  2342. entity,
  2343. source: entity.__featureRef.source || this.currentRenderedSource || "input",
  2344. featureIndex: entity.__featureRef.featureIndex,
  2345. selectOnly: true,
  2346. noDrag: true,
  2347. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2348. dragging: false,
  2349. };
  2350. return;
  2351. }
  2352. if (
  2353. (entity && entity.__vertexHandle && entity.__parentEntity) ||
  2354. (nearHandle && nearHandle.__vertexHandle && nearHandle.__parentEntity)
  2355. ) {
  2356. const handleEntity = nearHandle || entity;
  2357. const parent = handleEntity.__parentEntity;
  2358. if (!parent.__featureRef || typeof parent.__featureRef.featureIndex !== "number") {
  2359. this.resetPickDragState();
  2360. return;
  2361. }
  2362. const featureIndex = parent.__featureRef.featureIndex;
  2363. const source = parent.__featureRef.source || this.currentRenderedSource || "input";
  2364. const g = this.getSourceGeojsonData(source) || this.renderedGeojsonCache[source];
  2365. if (!g || !g.features || featureIndex < 0 || !g.features[featureIndex]) {
  2366. this.resetPickDragState();
  2367. return;
  2368. }
  2369. const geom = g.features[featureIndex].geometry;
  2370. if (!geom || geom.type === "MultiPolygon") {
  2371. this.resetPickDragState();
  2372. return;
  2373. }
  2374. // 避免每次点柄都 remove/recreate 顶点实体,防止与当前按下目标不同步、pick/hover 失效
  2375. if (!this.mapEditSelection || this.mapEditSelection.entity !== parent) {
  2376. this.applyMapEditSelection(parent);
  2377. }
  2378. const now = viewer.clock.currentTime;
  2379. const vi = handleEntity.__vertexIndex;
  2380. if (geom.type === "LineString" && parent.polyline && parent.polyline.positions) {
  2381. const positions = parent.polyline.positions.getValue(now);
  2382. if (!positions || !positions.length) {
  2383. this.resetPickDragState();
  2384. return;
  2385. }
  2386. let working = this.cloneCartesian3Array(positions);
  2387. let dragIndex = vi;
  2388. if (handleEntity.__handleType === "midpoint") {
  2389. const after = handleEntity.__insertAfter;
  2390. const insertAt = after + 1;
  2391. const midPos =
  2392. handleEntity.position && handleEntity.position.getValue
  2393. ? handleEntity.position.getValue(now)
  2394. : null;
  2395. if (after < 0 || insertAt > working.length || !midPos) {
  2396. this.resetPickDragState();
  2397. return;
  2398. }
  2399. working.splice(insertAt, 0, SkyScenery.Cartesian3.clone(midPos, new SkyScenery.Cartesian3()));
  2400. parent.polyline.positions = this.cloneCartesian3Array(working);
  2401. this.refreshVertexHandlesFromPositions(working);
  2402. dragIndex = insertAt;
  2403. }
  2404. if (dragIndex < 0 || dragIndex >= working.length) {
  2405. this.resetPickDragState();
  2406. return;
  2407. }
  2408. this._pickDrag = {
  2409. entity: parent,
  2410. source,
  2411. featureIndex,
  2412. geometryType: "LineString",
  2413. vertexIndex: dragIndex,
  2414. dragHandleEntity: handleEntity,
  2415. workingPositions: working,
  2416. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2417. cameraLocked: true,
  2418. dragging: false,
  2419. };
  2420. this.setScreenSpaceCameraForDrag(false);
  2421. this.applyVertexHandleStyles();
  2422. this.applyPointSelectionVisualByHoverPress();
  2423. return;
  2424. }
  2425. if (geom.type === "Polygon" && parent.polygon && parent.polygon.hierarchy) {
  2426. const hProp = parent.polygon.hierarchy;
  2427. const hier =
  2428. hProp && typeof hProp.getValue === "function" ? hProp.getValue(now) : hProp;
  2429. const positions = hier && hier.positions;
  2430. if (!positions || !positions.length) {
  2431. this.resetPickDragState();
  2432. return;
  2433. }
  2434. let working = this.cloneCartesian3Array(positions);
  2435. let dragIndex = vi;
  2436. if (handleEntity.__handleType === "midpoint") {
  2437. const after = handleEntity.__insertAfter;
  2438. const insertAt = after + 1;
  2439. const midPos =
  2440. handleEntity.position && handleEntity.position.getValue
  2441. ? handleEntity.position.getValue(now)
  2442. : null;
  2443. // insertAt === length 表示在末尾追加(闭合边上 v_last→v0 之间插点);用 >= 会误拒开环多边形
  2444. if (after < 0 || insertAt > working.length || !midPos) {
  2445. this.resetPickDragState();
  2446. return;
  2447. }
  2448. working.splice(insertAt, 0, SkyScenery.Cartesian3.clone(midPos, new SkyScenery.Cartesian3()));
  2449. this.syncPolygonEntityHierarchy(parent, working);
  2450. this.refreshVertexHandlesFromPositions(working);
  2451. dragIndex = insertAt;
  2452. }
  2453. if (dragIndex < 0 || dragIndex >= working.length) {
  2454. this.resetPickDragState();
  2455. return;
  2456. }
  2457. this._pickDrag = {
  2458. entity: parent,
  2459. source,
  2460. featureIndex,
  2461. geometryType: "Polygon",
  2462. vertexIndex: dragIndex,
  2463. dragHandleEntity: handleEntity,
  2464. workingPositions: working,
  2465. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2466. cameraLocked: true,
  2467. dragging: false,
  2468. };
  2469. this.setScreenSpaceCameraForDrag(false);
  2470. this.applyVertexHandleStyles();
  2471. this.applyPointSelectionVisualByHoverPress();
  2472. return;
  2473. }
  2474. this.resetPickDragState();
  2475. return;
  2476. }
  2477. if (!entity.__featureRef || typeof entity.__featureRef.featureIndex !== "number") {
  2478. this.resetPickDragState();
  2479. return;
  2480. }
  2481. const featureIndex = entity.__featureRef.featureIndex;
  2482. const source = entity.__featureRef.source || this.currentRenderedSource || "input";
  2483. const g = this.getSourceGeojsonData(source) || this.renderedGeojsonCache[source];
  2484. if (!g || !g.features || featureIndex < 0 || !g.features[featureIndex]) {
  2485. this.resetPickDragState();
  2486. return;
  2487. }
  2488. const geom = g.features[featureIndex].geometry;
  2489. if (!geom || geom.type === "MultiPolygon") {
  2490. this.resetPickDragState();
  2491. return;
  2492. }
  2493. const now = viewer.clock.currentTime;
  2494. const maxPx = 28;
  2495. if (entity.point && entity.position) {
  2496. const pos = entity.position.getValue(now);
  2497. if (!pos) {
  2498. this.resetPickDragState();
  2499. return;
  2500. }
  2501. if (this.screenDistanceToCartesian(event.position, pos) > maxPx) {
  2502. this.resetPickDragState();
  2503. return;
  2504. }
  2505. this.applyMapEditSelection(entity);
  2506. this._pickDrag = {
  2507. entity,
  2508. source,
  2509. featureIndex,
  2510. geometryType: "Point",
  2511. vertexIndex: 0,
  2512. dragHandleEntity: null,
  2513. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2514. cameraLocked: true,
  2515. dragging: false,
  2516. };
  2517. this.setScreenSpaceCameraForDrag(false);
  2518. this.applyPointSelectionVisualByHoverPress();
  2519. return;
  2520. }
  2521. if (entity.polyline && entity.polyline.positions) {
  2522. const positions = entity.polyline.positions.getValue(now);
  2523. if (!positions || !positions.length) {
  2524. this.resetPickDragState();
  2525. return;
  2526. }
  2527. const vi = this.findClosestVertexIndexScreen(positions, event.position, maxPx);
  2528. if (vi < 0) {
  2529. // 点在折线段上但未贴近任一顶点:仍选中并高亮,便于查看属性
  2530. this.applyMapEditSelection(entity);
  2531. this._pickDrag = {
  2532. entity,
  2533. source,
  2534. featureIndex,
  2535. geometryType: "LineString",
  2536. vertexIndex: -1,
  2537. selectOnly: true,
  2538. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2539. dragging: false,
  2540. };
  2541. return;
  2542. }
  2543. this.applyMapEditSelection(entity);
  2544. this._pickDrag = {
  2545. entity,
  2546. source,
  2547. featureIndex,
  2548. geometryType: "LineString",
  2549. vertexIndex: vi,
  2550. dragHandleEntity: this.vertexHandleEntities.find(
  2551. (h) => h.__handleType === "vertex" && h.__vertexIndex === vi
  2552. ),
  2553. workingPositions: this.cloneCartesian3Array(positions),
  2554. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2555. cameraLocked: true,
  2556. dragging: false,
  2557. };
  2558. this.setScreenSpaceCameraForDrag(false);
  2559. this.applyVertexHandleStyles();
  2560. return;
  2561. }
  2562. if (entity.polygon && entity.polygon.hierarchy) {
  2563. const hProp = entity.polygon.hierarchy;
  2564. const hier =
  2565. hProp && typeof hProp.getValue === "function" ? hProp.getValue(now) : hProp;
  2566. const positions = hier && hier.positions;
  2567. if (!positions || !positions.length) {
  2568. this.resetPickDragState();
  2569. return;
  2570. }
  2571. const vi = this.findClosestVertexIndexScreen(positions, event.position, maxPx);
  2572. if (vi < 0) {
  2573. // 点在面填充/边线上但未贴近顶点:仍选中高亮并显示全部顶点柄
  2574. this.applyMapEditSelection(entity);
  2575. this._pickDrag = {
  2576. entity,
  2577. source,
  2578. featureIndex,
  2579. geometryType: "Polygon",
  2580. vertexIndex: -1,
  2581. selectOnly: true,
  2582. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2583. dragging: false,
  2584. };
  2585. return;
  2586. }
  2587. this.applyMapEditSelection(entity);
  2588. this._pickDrag = {
  2589. entity,
  2590. source,
  2591. featureIndex,
  2592. geometryType: "Polygon",
  2593. vertexIndex: vi,
  2594. dragHandleEntity: this.vertexHandleEntities.find(
  2595. (h) => h.__handleType === "vertex" && h.__vertexIndex === vi
  2596. ),
  2597. workingPositions: this.cloneCartesian3Array(positions),
  2598. startScreen: new SkyScenery.Cartesian2(event.position.x, event.position.y),
  2599. cameraLocked: true,
  2600. dragging: false,
  2601. };
  2602. this.setScreenSpaceCameraForDrag(false);
  2603. this.applyVertexHandleStyles();
  2604. return;
  2605. }
  2606. this.resetPickDragState();
  2607. },
  2608. onPickDragMove(event) {
  2609. if (!this.geometryEditMode) {
  2610. const po = viewer.scene.pick(event.endPosition);
  2611. const ent = po && po.id && po.id.__featureRef ? po.id : null;
  2612. if (ent) {
  2613. this.applyHoveredFeatureStyle(ent);
  2614. } else {
  2615. this.clearHoveredFeatureStyle();
  2616. }
  2617. this.hideHoverHint();
  2618. return;
  2619. }
  2620. this.clearHoveredFeatureStyle();
  2621. const st = this._pickDrag;
  2622. const hoverNearHandle =
  2623. this.vertexHandleEntities && this.vertexHandleEntities.length
  2624. ? this.findNearestHandleByScreen(event.endPosition, 32)
  2625. : null;
  2626. if (st && st.entity && !st.selectOnly) {
  2627. const dx = event.endPosition.x - st.startScreen.x;
  2628. const dy = event.endPosition.y - st.startScreen.y;
  2629. const movedPx = Math.sqrt(dx * dx + dy * dy);
  2630. if (!st.dragging && movedPx > 1) {
  2631. st.dragging = true;
  2632. this.setScreenSpaceCameraForDrag(false);
  2633. this.enterInteractiveSceneRender();
  2634. }
  2635. if (st.dragging) {
  2636. const cart = this.pickSurfaceCartesian(event.endPosition);
  2637. if (cart) {
  2638. if (st.geometryType === "Point" && st.entity.position) {
  2639. st.entity.position = cart;
  2640. } else if (st.geometryType === "LineString" && st.workingPositions) {
  2641. const prev = st.workingPositions[st.vertexIndex];
  2642. const cPrev = SkyScenery.Cartographic.fromCartesian(prev);
  2643. const cNew = SkyScenery.Cartographic.fromCartesian(cart);
  2644. cNew.height = cPrev.height;
  2645. st.workingPositions[st.vertexIndex] = SkyScenery.Cartesian3.fromRadians(
  2646. cNew.longitude,
  2647. cNew.latitude,
  2648. cNew.height
  2649. );
  2650. st.entity.polyline.positions = st.workingPositions;
  2651. this.refreshVertexHandlesFromPositions(st.workingPositions);
  2652. } else if (st.geometryType === "Polygon" && st.workingPositions) {
  2653. const prev = st.workingPositions[st.vertexIndex];
  2654. const cPrev = SkyScenery.Cartographic.fromCartesian(prev);
  2655. const cNew = SkyScenery.Cartographic.fromCartesian(cart);
  2656. cNew.height = cPrev.height;
  2657. st.workingPositions[st.vertexIndex] = SkyScenery.Cartesian3.fromRadians(
  2658. cNew.longitude,
  2659. cNew.latitude,
  2660. cNew.height
  2661. );
  2662. const n = st.workingPositions.length;
  2663. // 仅当 positions 已带「首尾重合」闭合点时才同步;开环多边形首尾是不同角点,不能互拷否则会吞掉顶点
  2664. const ringClosedDuplicate =
  2665. n > 2 &&
  2666. SkyScenery.Cartesian3.distance(st.workingPositions[0], st.workingPositions[n - 1]) <
  2667. 0.5;
  2668. if (ringClosedDuplicate) {
  2669. if (st.vertexIndex === 0) {
  2670. st.workingPositions[n - 1] = SkyScenery.Cartesian3.clone(
  2671. st.workingPositions[0],
  2672. st.workingPositions[n - 1]
  2673. );
  2674. } else if (st.vertexIndex === n - 1) {
  2675. st.workingPositions[0] = SkyScenery.Cartesian3.clone(
  2676. st.workingPositions[n - 1],
  2677. st.workingPositions[0]
  2678. );
  2679. }
  2680. }
  2681. this.syncPolygonEntityHierarchy(st.entity, st.workingPositions);
  2682. this.refreshVertexHandlesFromPositions(st.workingPositions);
  2683. }
  2684. viewer.scene.requestRender();
  2685. }
  2686. }
  2687. }
  2688. // 相机默认先于自定义 handler 响应拖拽;在靠近顶点/中点或正在拖动节点时关闭相机输入,避免“拖地图”抢事件
  2689. const vertexInteraction =
  2690. !!(st && st.dragging) ||
  2691. !!(st && st.cameraLocked && st.entity && !st.selectOnly) ||
  2692. !!hoverNearHandle;
  2693. this.setScreenSpaceCameraForDrag(!vertexInteraction);
  2694. if (!(st && st.dragging)) {
  2695. this.updateVertexHoverFromPick(event.endPosition, hoverNearHandle);
  2696. } else {
  2697. this.applyVertexHandleStyles();
  2698. this.applyPointSelectionVisualByHoverPress();
  2699. }
  2700. },
  2701. onPickDragUp(event) {
  2702. const st = this._pickDrag;
  2703. if (!st || !st.entity) {
  2704. this.resetPickDragState();
  2705. return;
  2706. }
  2707. const wasDraggingGeometry = st.dragging;
  2708. const dx = event.position.x - st.startScreen.x;
  2709. const dy = event.position.y - st.startScreen.y;
  2710. const movedPx = Math.sqrt(dx * dx + dy * dy);
  2711. if (st.dragging) {
  2712. this.commitDraggedGeometryToGeojson(st);
  2713. this.syncJsonEditorData(st.source);
  2714. this.applyMapEditSelection(st.entity);
  2715. } else if (movedPx <= 5) {
  2716. this.openFeaturePropertyDialogForEntity(st.entity);
  2717. }
  2718. if (st.cameraLocked) {
  2719. this.setScreenSpaceCameraForDrag(true);
  2720. }
  2721. if (wasDraggingGeometry) {
  2722. this.exitInteractiveSceneRender();
  2723. }
  2724. this.resetPickDragState();
  2725. },
  2726. // 初始化地图要素拾取:单击打开属性;按住拖动顶点/点实时改坐标并同步 JSON
  2727. initFeaturePickHandler() {
  2728. if (this.featurePickHandler || !viewer || !viewer.canvas) {
  2729. return;
  2730. }
  2731. const h = new SkyScenery.ScreenSpaceEventHandler(viewer.canvas);
  2732. const SS = SkyScenery.ScreenSpaceEventType;
  2733. h.setInputAction((e) => this.tryBeginPickDrag(e), SS.LEFT_DOWN);
  2734. h.setInputAction((e) => this.onPickDragMove(e), SS.MOUSE_MOVE);
  2735. h.setInputAction((e) => this.onPickDragUp(e), SS.LEFT_UP);
  2736. this.featurePickHandler = h;
  2737. },
  2738. // 激活绘制工具
  2739. activateDraw(type) {
  2740. // 进入绘制工具时退出“更改绘制”模式,避免交互冲突
  2741. if (this.geometryEditMode) {
  2742. this.clearMapEditSelection();
  2743. }
  2744. // 取消镂空绘制模式
  2745. this.isDrawingHole = false;
  2746. // 如果已经是当前激活的工具,则取消激活
  2747. if (this.currentTool === type) {
  2748. this.deactivateDraw();
  2749. return;
  2750. }
  2751. // 先取消之前的绘制模式
  2752. this.deactivateDraw();
  2753. // 设置当前工具
  2754. this.currentTool = type;
  2755. this.drawingMode = type;
  2756. // 从当前渲染/编辑器数据同步几何,避免新绘制覆盖已有要素
  2757. this.syncGeometriesFromRenderedSource();
  2758. // 重置当前绘制状态
  2759. this.resetDrawingState();
  2760. switch (type) {
  2761. case "point":
  2762. this.drawPoint();
  2763. break;
  2764. case "polyline":
  2765. this.drawPolyline();
  2766. break;
  2767. case "polygon":
  2768. this.drawPolygon();
  2769. break;
  2770. }
  2771. if (type === "polyline" || type === "polygon") {
  2772. this.enterInteractiveSceneRender();
  2773. }
  2774. },
  2775. // 重置绘制状态
  2776. resetDrawingState() {
  2777. this.currentPositions = [];
  2778. this.currentEntity = null;
  2779. // 移除临时预览实体
  2780. if (this.tempEntity) {
  2781. viewer.entities.remove(this.tempEntity);
  2782. viewer.scene.requestRender();
  2783. this.tempEntity = null;
  2784. }
  2785. },
  2786. // 取消绘制模式
  2787. deactivateDraw() {
  2788. this.exitInteractiveSceneRender();
  2789. if (this.handler) {
  2790. // 移除所有事件监听器
  2791. this.handler.removeInputAction(SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  2792. this.handler.removeInputAction(SkyScenery.ScreenSpaceEventType.MOUSE_MOVE);
  2793. this.handler.removeInputAction(SkyScenery.ScreenSpaceEventType.RIGHT_CLICK);
  2794. }
  2795. // 重置状态
  2796. this.resetDrawingState();
  2797. this.currentTool = null;
  2798. this.drawingMode = null;
  2799. this.isDrawingHole = false;
  2800. },
  2801. // 绘制点
  2802. drawPoint() {
  2803. const that = this;
  2804. this.handler.setInputAction(function (event) {
  2805. const position = that.pickSurfaceCartesian(event.position);
  2806. if (position) {
  2807. const cartographic = SkyScenery.Cartographic.fromCartesian(position);
  2808. const longitude = SkyScenery.Math.toDegrees(cartographic.longitude);
  2809. const latitude = SkyScenery.Math.toDegrees(cartographic.latitude);
  2810. // 创建点实体(实时渲染)
  2811. const entity = viewer.entities.add({
  2812. position: position,
  2813. point: {
  2814. show: true,
  2815. color: SkyScenery.Color.RED,
  2816. pixelSize: 10,
  2817. outlineColor: SkyScenery.Color.WHITE,
  2818. outlineWidth: 2,
  2819. },
  2820. });
  2821. viewer.scene.requestRender();
  2822. that.drawnEntities.push(entity);
  2823. // 转换为geometry格式并保存
  2824. const geometry = {
  2825. type: "Point",
  2826. coordinates: that.lonLatToGeoJsonCoord(longitude, latitude, "point"),
  2827. };
  2828. that.geometries.push(geometry);
  2829. that.changeGeometries();
  2830. const source = "input";
  2831. const featureIndex = that.geometries.length - 1;
  2832. entity.__featureRef = { source, featureIndex };
  2833. entity.__featureProperties = {};
  2834. console.log("绘制了点:", geometry);
  2835. }
  2836. }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  2837. },
  2838. // 绘制线
  2839. drawPolyline() {
  2840. const that = this;
  2841. // 鼠标移动时更新临时线(实时渲染预览)
  2842. this.handler.setInputAction(function (event) {
  2843. if (that.currentPositions.length > 0) {
  2844. const endPosition = that.pickSurfaceCartesian(event.endPosition);
  2845. if (endPosition) {
  2846. const last = that.currentPositions[that.currentPositions.length - 1];
  2847. const pendingSeg = [last, endPosition];
  2848. // 待落点使用虚线预览
  2849. if (!that.tempEntity) {
  2850. that.tempEntity = viewer.entities.add({
  2851. polyline: {
  2852. show: true,
  2853. positions: pendingSeg,
  2854. material: new SkyScenery.PolylineDashMaterialProperty({
  2855. color: SkyScenery.Color.RED.withAlpha(0.9),
  2856. dashLength: 10,
  2857. }),
  2858. width: 3,
  2859. clampToGround: true,
  2860. },
  2861. });
  2862. viewer.scene.requestRender();
  2863. } else {
  2864. that.tempEntity.polyline.positions = pendingSeg;
  2865. viewer.scene.requestRender();
  2866. }
  2867. }
  2868. }
  2869. }, SkyScenery.ScreenSpaceEventType.MOUSE_MOVE);
  2870. // 左键点击添加点
  2871. this.handler.setInputAction(function (event) {
  2872. const position = that.pickSurfaceCartesian(event.position);
  2873. if (position) {
  2874. that.currentPositions.push(position.clone());
  2875. // 已落点使用实线
  2876. if (that.currentPositions.length > 1) {
  2877. if (!that.currentEntity) {
  2878. that.currentEntity = viewer.entities.add({
  2879. polyline: {
  2880. show: true,
  2881. positions: [...that.currentPositions],
  2882. material: SkyScenery.Color.RED,
  2883. width: 3,
  2884. clampToGround: true,
  2885. },
  2886. });
  2887. } else {
  2888. that.currentEntity.polyline.positions = [...that.currentPositions];
  2889. }
  2890. viewer.scene.requestRender();
  2891. }
  2892. }
  2893. }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  2894. // 右键点击完成绘制
  2895. this.handler.setInputAction(function () {
  2896. if (that.currentPositions.length > 1) {
  2897. // 移除临时预览实体
  2898. if (that.tempEntity) {
  2899. viewer.entities.remove(that.tempEntity);
  2900. that.tempEntity = null;
  2901. }
  2902. // 否则创建线
  2903. // 确保当前实体存在
  2904. if (!that.currentEntity) {
  2905. that.currentEntity = viewer.entities.add({
  2906. polyline: {
  2907. show: true,
  2908. positions: [...that.currentPositions],
  2909. material: SkyScenery.Color.RED,
  2910. width: 3,
  2911. clampToGround: true,
  2912. },
  2913. });
  2914. }
  2915. that.drawnEntities.push(that.currentEntity);
  2916. viewer.scene.requestRender();
  2917. // 转换为geometry格式并保存
  2918. const coordinates = [];
  2919. that.currentPositions.forEach((pos) => {
  2920. const cartographic = SkyScenery.Cartographic.fromCartesian(pos);
  2921. coordinates.push(
  2922. that.lonLatToGeoJsonCoord(
  2923. SkyScenery.Math.toDegrees(cartographic.longitude),
  2924. SkyScenery.Math.toDegrees(cartographic.latitude),
  2925. "polyline"
  2926. )
  2927. );
  2928. });
  2929. const geometry = {
  2930. type: "LineString",
  2931. coordinates: coordinates,
  2932. };
  2933. that.geometries.push(geometry);
  2934. that.changeGeometries();
  2935. const source = "input";
  2936. const featureIndex = that.geometries.length - 1;
  2937. that.currentEntity.__featureRef = { source, featureIndex };
  2938. that.currentEntity.__featureProperties = {};
  2939. console.log("绘制了线:", geometry);
  2940. // 取消当前绘制模式
  2941. that.deactivateDraw();
  2942. }
  2943. }, SkyScenery.ScreenSpaceEventType.RIGHT_CLICK);
  2944. },
  2945. // 绘制面
  2946. drawPolygon() {
  2947. const that = this;
  2948. // 鼠标移动时更新临时面(实时渲染预览)
  2949. this.handler.setInputAction(function (event) {
  2950. if (that.currentPositions.length > 0) {
  2951. const endPosition = that.pickSurfaceCartesian(event.endPosition);
  2952. if (endPosition) {
  2953. const last = that.currentPositions[that.currentPositions.length - 1];
  2954. const first = that.currentPositions[0];
  2955. const pending = [last, endPosition, first];
  2956. // 待落点边使用虚线
  2957. if (!that.tempEntity) {
  2958. that.tempEntity = viewer.entities.add({
  2959. polyline: {
  2960. show: true,
  2961. positions: pending,
  2962. material: new SkyScenery.PolylineDashMaterialProperty({
  2963. color: SkyScenery.Color.RED.withAlpha(0.95),
  2964. dashLength: 10,
  2965. }),
  2966. width: 3,
  2967. clampToGround: true,
  2968. },
  2969. });
  2970. viewer.scene.requestRender();
  2971. } else {
  2972. that.tempEntity.polyline.positions = pending;
  2973. viewer.scene.requestRender();
  2974. }
  2975. }
  2976. }
  2977. }, SkyScenery.ScreenSpaceEventType.MOUSE_MOVE);
  2978. // 左键点击添加点
  2979. this.handler.setInputAction(function (event) {
  2980. const position = that.pickSurfaceCartesian(event.position);
  2981. if (position) {
  2982. // 检查是否点击了第一个点附近(自动闭合)
  2983. if (
  2984. that.currentPositions.length > 2 &&
  2985. that.isPositionNearFirst(position, that.currentPositions[0])
  2986. ) {
  2987. // 完成多边形绘制
  2988. that.finalizePolygonDrawing();
  2989. that.deactivateDraw();
  2990. return;
  2991. }
  2992. that.currentPositions.push(position.clone());
  2993. // 至少两个点时先显示已落点实线(第三个点后切换为实面+实边)
  2994. if (that.currentPositions.length === 2) {
  2995. const linePositions = [...that.currentPositions];
  2996. if (!that.currentEntity || !that.currentEntity.polyline) {
  2997. if (that.currentEntity) {
  2998. viewer.entities.remove(that.currentEntity);
  2999. }
  3000. that.currentEntity = viewer.entities.add({
  3001. polyline: {
  3002. show: true,
  3003. positions: linePositions,
  3004. material: SkyScenery.Color.RED,
  3005. width: 3,
  3006. clampToGround: true,
  3007. },
  3008. });
  3009. } else {
  3010. that.currentEntity.polyline.positions = linePositions;
  3011. }
  3012. viewer.scene.requestRender();
  3013. } else if (that.currentPositions.length > 2) {
  3014. // 闭合多边形
  3015. const closedPositions = [...that.currentPositions, that.currentPositions[0]];
  3016. if (!that.currentEntity) {
  3017. that.currentEntity = viewer.entities.add({
  3018. polygon: {
  3019. show: true,
  3020. hierarchy: new SkyScenery.PolygonHierarchy(closedPositions),
  3021. material: SkyScenery.Color.RED.withAlpha(0.35),
  3022. outline: true,
  3023. outlineColor: SkyScenery.Color.RED,
  3024. outlineWidth: 2,
  3025. },
  3026. });
  3027. } else if (that.currentEntity.polygon) {
  3028. that.currentEntity.polygon.hierarchy = new SkyScenery.PolygonHierarchy(closedPositions);
  3029. } else {
  3030. // 第二点阶段是线实体,第三点开始改为面实体
  3031. viewer.entities.remove(that.currentEntity);
  3032. that.currentEntity = viewer.entities.add({
  3033. polygon: {
  3034. show: true,
  3035. hierarchy: new SkyScenery.PolygonHierarchy(closedPositions),
  3036. material: SkyScenery.Color.RED.withAlpha(0.35),
  3037. outline: true,
  3038. outlineColor: SkyScenery.Color.RED,
  3039. outlineWidth: 2,
  3040. },
  3041. });
  3042. }
  3043. viewer.scene.requestRender();
  3044. }
  3045. }
  3046. }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  3047. // 右键点击完成绘制
  3048. this.handler.setInputAction(function () {
  3049. if (that.currentPositions.length > 2) {
  3050. that.finalizePolygonDrawing();
  3051. // 取消当前绘制模式
  3052. that.deactivateDraw();
  3053. }
  3054. }, SkyScenery.ScreenSpaceEventType.RIGHT_CLICK);
  3055. },
  3056. // 完成多边形绘制
  3057. finalizePolygonDrawing() {
  3058. // 移除临时预览实体
  3059. if (this.tempEntity) {
  3060. viewer.entities.remove(this.tempEntity);
  3061. this.tempEntity = null;
  3062. }
  3063. // 确保多边形是闭合的
  3064. let closedPositions = [...this.currentPositions];
  3065. // 创建最终的多边形实体
  3066. if (this.currentEntity) {
  3067. viewer.entities.remove(this.currentEntity);
  3068. }
  3069. this.currentEntity = viewer.entities.add({
  3070. polygon: {
  3071. show: true,
  3072. hierarchy: new SkyScenery.PolygonHierarchy(closedPositions),
  3073. material: SkyScenery.Color.RED.withAlpha(0.5),
  3074. outline: true,
  3075. outlineColor: SkyScenery.Color.BLUE,
  3076. outlineWidth: 2,
  3077. },
  3078. });
  3079. viewer.scene.requestRender();
  3080. this.drawnEntities.push(this.currentEntity);
  3081. // 转换为geometry格式并保存(不包含重复的最后一个点)
  3082. const coordinates = [];
  3083. const mainRing = [];
  3084. for (let i = 0; i < closedPositions.length; i++) {
  3085. const cartographic = SkyScenery.Cartographic.fromCartesian(closedPositions[i]);
  3086. mainRing.push(
  3087. this.lonLatToGeoJsonCoord(
  3088. SkyScenery.Math.toDegrees(cartographic.longitude),
  3089. SkyScenery.Math.toDegrees(cartographic.latitude),
  3090. "polygon"
  3091. )
  3092. );
  3093. }
  3094. const cartographic = SkyScenery.Cartographic.fromCartesian(closedPositions[0]);
  3095. mainRing.push(
  3096. this.lonLatToGeoJsonCoord(
  3097. SkyScenery.Math.toDegrees(cartographic.longitude),
  3098. SkyScenery.Math.toDegrees(cartographic.latitude),
  3099. "polygon"
  3100. )
  3101. );
  3102. coordinates.push(mainRing);
  3103. const geometry = {
  3104. type: "Polygon",
  3105. coordinates: coordinates, // GeoJSON格式
  3106. holes: [], // 用于存储镂空区域
  3107. };
  3108. // 保存实体和几何对象的关联
  3109. this.currentEntity.geometryRef = geometry;
  3110. this.geometries.push(geometry);
  3111. this.changeGeometries();
  3112. const source = "input";
  3113. const featureIndex = this.geometries.length - 1;
  3114. this.currentEntity.__featureRef = { source, featureIndex };
  3115. this.currentEntity.__featureProperties = {};
  3116. console.log("绘制了面:", geometry);
  3117. },
  3118. // 开始绘制镂空
  3119. startHoleDrawing() {
  3120. // 如果已经在绘制镂空,则取消
  3121. if (this.isDrawingHole) {
  3122. this.isDrawingHole = false;
  3123. this.deactivateDraw();
  3124. return;
  3125. }
  3126. // 取消其他绘制模式
  3127. this.deactivateDraw();
  3128. // 设置为镂空绘制模式
  3129. this.isDrawingHole = true;
  3130. console.log("请点击一个多边形以添加镂空");
  3131. // 设置点击事件选择多边形
  3132. const that = this;
  3133. this.handler.setInputAction(function (event) {
  3134. // 拾取实体
  3135. const pickedObject = viewer.scene.pick(event.position);
  3136. if (pickedObject && pickedObject.id && pickedObject.id.polygon) {
  3137. const polygonEntity = pickedObject.id;
  3138. // 检查是否有对应的几何对象
  3139. if (polygonEntity.geometryRef && polygonEntity.geometryRef.type === "Polygon") {
  3140. that.currentPolygonEntity = polygonEntity;
  3141. that.currentPolygonGeometry = polygonEntity.geometryRef;
  3142. console.log("已选择多边形,现在绘制镂空区域");
  3143. // 开始绘制镂空区域(使用多边形绘制逻辑,但最后添加为镂空)
  3144. that.resetDrawingState();
  3145. that.drawHole();
  3146. } else {
  3147. console.log("选择的不是有效的多边形");
  3148. }
  3149. } else {
  3150. console.log("未选中任何多边形");
  3151. }
  3152. }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  3153. },
  3154. // 绘制镂空区域
  3155. drawHole() {
  3156. const that = this;
  3157. this.enterInteractiveSceneRender();
  3158. // 清除之前的事件
  3159. this.handler.removeInputAction(SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  3160. // 鼠标移动时更新临时镂空区域
  3161. this.handler.setInputAction(function (event) {
  3162. if (that.currentPositions.length > 0) {
  3163. const endPosition = that.pickSurfaceCartesian(event.endPosition);
  3164. if (endPosition) {
  3165. // 为了预览效果,临时闭合多边形
  3166. const tempPositions = [...that.currentPositions, endPosition, that.currentPositions[0]];
  3167. // 更新临时预览实体
  3168. if (!that.tempEntity) {
  3169. that.tempEntity = viewer.entities.add({
  3170. polygon: {
  3171. show: true,
  3172. hierarchy: new SkyScenery.PolygonHierarchy(tempPositions),
  3173. material: new SkyScenery.ColorMaterialProperty(
  3174. new SkyScenery.Color(1, 0, 0, 0.3)
  3175. ),
  3176. outline: true,
  3177. outlineColor: SkyScenery.Color.RED,
  3178. outlineWidth: 2,
  3179. },
  3180. });
  3181. viewer.scene.requestRender();
  3182. } else {
  3183. that.tempEntity.polygon.hierarchy = new SkyScenery.PolygonHierarchy(tempPositions);
  3184. }
  3185. }
  3186. }
  3187. }, SkyScenery.ScreenSpaceEventType.MOUSE_MOVE);
  3188. // 左键点击添加点
  3189. this.handler.setInputAction(function (event) {
  3190. const position = that.pickSurfaceCartesian(event.position);
  3191. if (position) {
  3192. // 检查是否点击了第一个点附近(自动闭合)
  3193. if (
  3194. that.currentPositions.length > 2 &&
  3195. that.isPositionNearFirst(position, that.currentPositions[0])
  3196. ) {
  3197. // 完成镂空绘制
  3198. that.finalizeHoleDrawing();
  3199. return;
  3200. }
  3201. that.currentPositions.push(position.clone());
  3202. }
  3203. }, SkyScenery.ScreenSpaceEventType.LEFT_CLICK);
  3204. // 右键点击完成绘制
  3205. this.handler.setInputAction(function () {
  3206. if (that.currentPositions.length > 2) {
  3207. that.finalizeHoleDrawing();
  3208. }
  3209. }, SkyScenery.ScreenSpaceEventType.RIGHT_CLICK);
  3210. },
  3211. // 完成镂空绘制
  3212. finalizeHoleDrawing() {
  3213. // 移除临时预览实体
  3214. if (this.tempEntity) {
  3215. viewer.entities.remove(this.tempEntity);
  3216. viewer.scene.requestRender();
  3217. this.tempEntity = null;
  3218. }
  3219. // 确保镂空区域是闭合的
  3220. let closedPositions = [...this.currentPositions];
  3221. // 转换为几何坐标
  3222. const holeCoordinates = [];
  3223. for (let i = 0; i < closedPositions.length; i++) {
  3224. const cartographic = SkyScenery.Cartographic.fromCartesian(closedPositions[i]);
  3225. holeCoordinates.push(
  3226. this.lonLatToGeoJsonCoord(
  3227. SkyScenery.Math.toDegrees(cartographic.longitude),
  3228. SkyScenery.Math.toDegrees(cartographic.latitude),
  3229. "polygon"
  3230. )
  3231. );
  3232. }
  3233. const cartographic = SkyScenery.Cartographic.fromCartesian(closedPositions[0]);
  3234. holeCoordinates.push(
  3235. this.lonLatToGeoJsonCoord(
  3236. SkyScenery.Math.toDegrees(cartographic.longitude),
  3237. SkyScenery.Math.toDegrees(cartographic.latitude),
  3238. "polygon"
  3239. )
  3240. );
  3241. // 添加到几何对象的镂空数组
  3242. if (!this.currentPolygonGeometry.holes) {
  3243. this.currentPolygonGeometry.holes = [];
  3244. }
  3245. this.currentPolygonGeometry.holes.push(holeCoordinates);
  3246. // 更新多边形的层级结构以包含镂空
  3247. const polygonHierarchy = this.buildPolygonHierarchyWithHoles(
  3248. this.currentPolygonGeometry.coordinates[0],
  3249. this.currentPolygonGeometry.holes
  3250. );
  3251. // 更新实体显示
  3252. this.currentPolygonEntity.polygon.hierarchy = polygonHierarchy;
  3253. console.log("添加了镂空区域:", holeCoordinates);
  3254. console.log("更新后的多边形几何:", this.currentPolygonGeometry);
  3255. // 重置状态
  3256. this.resetDrawingState();
  3257. this.isDrawingHole = false;
  3258. this.currentPolygonEntity = null;
  3259. this.currentPolygonGeometry = null;
  3260. // 取消绘制模式
  3261. this.deactivateDraw();
  3262. },
  3263. // 构建包含镂空的多边形层级结构
  3264. buildPolygonHierarchyWithHoles(outerRing, holes) {
  3265. // 将外部环转换为Cartesian3数组
  3266. const outerRingPositions = [];
  3267. outerRing.forEach((coord) => {
  3268. const z =
  3269. coord.length > 2 && typeof coord[2] === "number" ? coord[2] : 0;
  3270. const cartesian = SkyScenery.Cartesian3.fromDegrees(coord[0], coord[1], z);
  3271. outerRingPositions.push(cartesian);
  3272. });
  3273. // 闭合外部环
  3274. outerRingPositions.push(outerRingPositions[0]);
  3275. // 创建层级结构
  3276. const hierarchy = new SkyScenery.PolygonHierarchy(outerRingPositions);
  3277. // 添加镂空
  3278. if (holes && holes.length > 0) {
  3279. hierarchy.holes = holes.map((hole) => {
  3280. const holePositions = [];
  3281. hole.forEach((coord) => {
  3282. const z =
  3283. coord.length > 2 && typeof coord[2] === "number" ? coord[2] : 0;
  3284. const cartesian = SkyScenery.Cartesian3.fromDegrees(coord[0], coord[1], z);
  3285. holePositions.push(cartesian);
  3286. });
  3287. // 闭合镂空环
  3288. holePositions.push(holePositions[0]);
  3289. return new SkyScenery.PolygonHierarchy(holePositions);
  3290. });
  3291. }
  3292. return hierarchy;
  3293. },
  3294. // 检查点是否靠近第一个点
  3295. isPositionNearFirst(position, firstPosition, tolerance = 10) {
  3296. // 单位:米
  3297. const distance = SkyScenery.Cartesian3.distance(position, firstPosition);
  3298. return distance < tolerance;
  3299. },
  3300. changeGeometries() {
  3301. let requestData = {};
  3302. const geometriesToSend = this.geometries;
  3303. const baseFeatures =
  3304. this.jsonData && Array.isArray(this.jsonData.features) ? this.jsonData.features : [];
  3305. let FeatureCollectionFeatures = [];
  3306. geometriesToSend.forEach((item, idx) => {
  3307. const base = baseFeatures[idx] || {};
  3308. FeatureCollectionFeatures.push({
  3309. type: "Feature",
  3310. properties: base.properties ? JSON.parse(JSON.stringify(base.properties)) : {},
  3311. geometry: {
  3312. type: item.type,
  3313. coordinates: item.coordinates,
  3314. },
  3315. });
  3316. });
  3317. // 构造请求数据
  3318. requestData = {
  3319. type: "FeatureCollection",
  3320. features: FeatureCollectionFeatures,
  3321. timestamp: new Date().getTime(),
  3322. };
  3323. if (
  3324. this.SceneValue &&
  3325. this.dmsServerItem &&
  3326. this.dmsServerItem.elementTypes &&
  3327. this.ifHasType("unit") &&
  3328. this.params.unit
  3329. ) {
  3330. requestData.unit = this.params.unit;
  3331. }
  3332. if (
  3333. this.SceneValue &&
  3334. this.dmsServerItem &&
  3335. this.dmsServerItem.elementTypes &&
  3336. this.ifHasType("EPSILON") &&
  3337. this.params.EPSILON
  3338. ) {
  3339. requestData.EPSILON = this.params.EPSILON;
  3340. }
  3341. if (
  3342. this.SceneValue &&
  3343. this.dmsServerItem &&
  3344. this.dmsServerItem.elementTypes &&
  3345. this.ifHasType("inPrj") &&
  3346. this.params.inPrj
  3347. ) {
  3348. requestData.inPrj = this.params.inPrj;
  3349. }
  3350. if (
  3351. this.SceneValue &&
  3352. this.dmsServerItem &&
  3353. this.dmsServerItem.elementTypes &&
  3354. this.ifHasType("compressionRatio") &&
  3355. this.params.compressionRatio
  3356. ) {
  3357. requestData.compressionRatio = this.params.compressionRatio;
  3358. }
  3359. if (
  3360. this.SceneValue &&
  3361. this.dmsServerItem &&
  3362. this.dmsServerItem.elementTypes &&
  3363. this.ifHasType("outPrj") &&
  3364. this.params.outPrj
  3365. ) {
  3366. requestData.outPrj = this.params.outPrj;
  3367. }
  3368. if (
  3369. this.SceneValue &&
  3370. this.dmsServerItem &&
  3371. this.dmsServerItem.elementTypes &&
  3372. this.ifHasType("distance") &&
  3373. this.params.distance
  3374. ) {
  3375. requestData.distance = this.params.distance;
  3376. }
  3377. this.jsonData = requestData;
  3378. },
  3379. // 发送几何数据到后台接口
  3380. sendGeometriesToBackend() {
  3381. // 这里使用axios发送请求,需要确保项目中已安装并导入axios
  3382. if (!this.dmsServerItem || !this.dmsServerItem.apiUrl) {
  3383. this.$message({
  3384. message: "请先选择有效场景并加载接口信息",
  3385. type: "warning",
  3386. });
  3387. return;
  3388. }
  3389. let requestData;
  3390. this.backData = {};
  3391. let requestUrl = this.dmsServerItem.apiUrl;
  3392. if (this.ifHasType("point") || this.ifHasType("polyline") || this.ifHasType("polygon")) {
  3393. const check = this.validateSendGeometryParams();
  3394. if (!check.ok) {
  3395. this.$message({
  3396. message: check.message,
  3397. type: "warning",
  3398. });
  3399. return;
  3400. }
  3401. requestData = this.jsonData;
  3402. } else {
  3403. requestData = new FormData();
  3404. this.dmsServerItem.elementTypes.forEach((key) => {
  3405. if (key == "file") {
  3406. if (!this.currentFile) {
  3407. return this.$message({
  3408. message: "请选择文件",
  3409. type: "error",
  3410. });
  3411. }
  3412. requestData.append("file", this.currentFile.raw);
  3413. } else {
  3414. requestData.append(key, this.params[key]);
  3415. }
  3416. });
  3417. requestData.append("token", localStorage.getItem("token"));
  3418. }
  3419. let that = this;
  3420. // 实际项目中使用以下代码发送请求
  3421. wgn
  3422. .topology(requestUrl, requestData)
  3423. .then((res) => {
  3424. if (requestUrl.indexOf("downloadFile") == -1) {
  3425. that.backData = res;
  3426. if (res.code && res.code == 200) {
  3427. that.$message({
  3428. message: res.message,
  3429. type: "success",
  3430. });
  3431. const downPath = that.pickDownFilePathFromResponse(res);
  3432. if (downPath) {
  3433. that.$nextTick(() => {
  3434. that.downloadConvertedFile(downPath);
  3435. });
  3436. }
  3437. } else {
  3438. that.$message({
  3439. message: res.content,
  3440. type: "error",
  3441. });
  3442. }
  3443. } else {
  3444. const blob = res; // 响应体是 Blob 类型
  3445. if (!blob) {
  3446. that.$message.error("下载失败:文件流为空");
  3447. reject("文件流为空");
  3448. return;
  3449. }
  3450. let _downloadFile = that.params.filePath + "";
  3451. let fileName = _downloadFile.substring(_downloadFile.indexOf("down_files") + 11);
  3452. // D:\work\backCode\one_map_portal_server\down_files\0378b1c2e92a4c36ab447f552c0c7888.xlsx
  3453. // 替换原代码中创建 url 的逻辑,先加校验
  3454. console.log("blob 类型:", Object.prototype.toString.call(blob)); // 正常应输出 [object Blob]
  3455. console.log("blob 大小:", blob.size); // 正常应大于 0
  3456. if (!(blob instanceof Blob) || blob.size === 0) {
  3457. this.$message.error("文件流解析失败,无法生成下载链接");
  3458. return;
  3459. }
  3460. const url = window.URL.createObjectURL(blob); // 将 Blob 转为临时 URL
  3461. const link = document.createElement("a");
  3462. link.href = url;
  3463. link.download = fileName; // 设置下载文件名
  3464. link.style.display = "none";
  3465. document.body.appendChild(link);
  3466. link.click(); // 触发点击下载
  3467. document.body.removeChild(link);
  3468. window.URL.revokeObjectURL(url); // 销毁临时 URL,避免内存泄漏
  3469. }
  3470. })
  3471. .catch((error) => {
  3472. console.error("后台接口调用失败:", error);
  3473. });
  3474. },
  3475. /**
  3476. * 从接口返回 JSON 中解析 downFilePath(支持 content 为对象或 JSON 字符串、或顶层字段)。
  3477. */
  3478. pickDownFilePathFromResponse(res) {
  3479. if (!res || typeof res !== "object") {
  3480. return null;
  3481. }
  3482. const tryVal = (v) => {
  3483. if (typeof v !== "string") {
  3484. return null;
  3485. }
  3486. const s = v.trim();
  3487. if (!s || s.indexOf("未知文件") !== -1) {
  3488. return null;
  3489. }
  3490. return s;
  3491. };
  3492. let p = tryVal(res.downFilePath);
  3493. if (p) {
  3494. return p;
  3495. }
  3496. const c = res.content;
  3497. if (c && typeof c === "object") {
  3498. p = tryVal(c.downFilePath);
  3499. if (p) {
  3500. return p;
  3501. }
  3502. }
  3503. if (typeof c === "string") {
  3504. try {
  3505. const parsed = JSON.parse(c);
  3506. if (parsed && typeof parsed === "object") {
  3507. p = tryVal(parsed.downFilePath);
  3508. if (p) {
  3509. return p;
  3510. }
  3511. }
  3512. } catch (e) {
  3513. /* ignore */
  3514. }
  3515. }
  3516. return null;
  3517. },
  3518. /** 根据后端返回的 downFilePath,请求 downloadFile 并触发浏览器下载(与「下载文件」场景一致) */
  3519. downloadConvertedFile(serverFilePath) {
  3520. const base =
  3521. typeof systemConfig !== "undefined" && systemConfig.baseServicerPath
  3522. ? systemConfig.baseServicerPath
  3523. : "";
  3524. const url = base + "/spatiotemporal_data_format_conversion/downloadFile";
  3525. getFile(url, { filePath: serverFilePath })
  3526. .then((blob) => {
  3527. if (!(blob instanceof Blob) || blob.size === 0) {
  3528. this.$message.warning(
  3529. "转换文件下载失败(空流),请从返回 JSON 的 downFilePath 手动获取"
  3530. );
  3531. return;
  3532. }
  3533. const name = this.fileNameFromPath(serverFilePath);
  3534. const href = window.URL.createObjectURL(blob);
  3535. const link = document.createElement("a");
  3536. link.href = href;
  3537. link.download = name;
  3538. link.style.display = "none";
  3539. document.body.appendChild(link);
  3540. link.click();
  3541. document.body.removeChild(link);
  3542. window.URL.revokeObjectURL(href);
  3543. this.$message.success("已开始下载转换文件:" + name);
  3544. })
  3545. .catch((e) => {
  3546. console.error(e);
  3547. this.$message.error("转换文件下载失败");
  3548. });
  3549. },
  3550. fileNameFromPath(fullPath) {
  3551. if (!fullPath) {
  3552. return "download";
  3553. }
  3554. const s = String(fullPath).replace(/\\/g, "/");
  3555. const i = s.lastIndexOf("/");
  3556. return i >= 0 ? s.slice(i + 1) : s;
  3557. },
  3558. // 清除所有绘制的元素,并更新geometries
  3559. clearAll() {
  3560. this.clearAllMap();
  3561. this.changeGeometries();
  3562. },
  3563. // 清除所有绘制的元素
  3564. clearAllMap() {
  3565. this.removeVertexHandleEntities();
  3566. this.mapEditSelection = null;
  3567. this.hoveredVertexIndex = -1;
  3568. this.hoveredHandleEntity = null;
  3569. this.clearHoveredFeatureStyle();
  3570. this.geometryEditMode = false;
  3571. this.pickedFeatureRef = null;
  3572. this.hideHoverHint();
  3573. // 移除所有实体
  3574. this.drawnEntities.forEach((entity) => {
  3575. viewer.entities.remove(entity);
  3576. });
  3577. viewer.scene.requestRender();
  3578. // 清空数组
  3579. this.drawnEntities = [];
  3580. this.geometries = [];
  3581. this.currentRenderedSource = "";
  3582. this.propertyDialog.visible = false;
  3583. this.propertyDialog.list = [];
  3584. this.propertyDialog.source = "";
  3585. this.propertyDialog.propertiesRef = null;
  3586. this.propertyDialog.featureIndex = -1;
  3587. this.resetPickDragState();
  3588. this.setScreenSpaceCameraForDrag(true);
  3589. // 取消当前绘制模式
  3590. this.deactivateDraw();
  3591. console.log("已清除所有绘制的元素");
  3592. },
  3593. },
  3594. };
  3595. </script>
  3596. <style lang="less" scoped>
  3597. // 操作栏样式
  3598. #controlPanelBox {
  3599. width: calc(30vw - 2rem);
  3600. min-width: 500px;
  3601. height: calc(100vh - 2rem);
  3602. display: flex;
  3603. flex-direction: column;
  3604. padding: 1rem;
  3605. position: fixed;
  3606. top: 0px;
  3607. right: 0;
  3608. background: #08224a;
  3609. }
  3610. // 绘制按钮区域
  3611. .toolbar {
  3612. position: absolute;
  3613. top: 10px;
  3614. left: -120px;
  3615. z-index: 1000;
  3616. background: #08224a;
  3617. border-radius: 8px;
  3618. padding: 3px 5px;
  3619. box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
  3620. display: flex;
  3621. flex-direction: column;
  3622. gap: 8px;
  3623. }
  3624. .tool-item {
  3625. padding: 10px 20px;
  3626. cursor: pointer;
  3627. border-radius: 4px;
  3628. transition: all 0.3s ease;
  3629. user-select: none;
  3630. font-size: 14px;
  3631. }
  3632. .tool-item:hover {
  3633. background: #ffffff32;
  3634. }
  3635. .tool-item.active {
  3636. background: #409eff;
  3637. color: white;
  3638. }
  3639. .sceneNameBox {
  3640. display: flex;
  3641. align-items: center;
  3642. justify-content: space-between;
  3643. }
  3644. .vueJsonEditor_box {
  3645. width: 100%;
  3646. height: 100%;
  3647. position: relative;
  3648. }
  3649. .vueJsonEditor_tools {
  3650. position: absolute;
  3651. top: 8px;
  3652. right: 10px;
  3653. font-size: 14px;
  3654. z-index: 1;
  3655. color: #fff;
  3656. }
  3657. .vueJsonEditor_tools span {
  3658. padding: 2px 5px;
  3659. opacity: 0.8;
  3660. cursor: pointer;
  3661. border: 1px solid #ffffff00;
  3662. border-radius: 2px;
  3663. margin-right: 5px;
  3664. &:hover {
  3665. background-color: rgba(255, 255, 255, 0.2);
  3666. border-color: rgba(255, 255, 255, 0.4);
  3667. }
  3668. }
  3669. .feature-property-content {
  3670. max-height: 360px;
  3671. overflow: auto;
  3672. padding-right: 4px;
  3673. }
  3674. .feature-property-tip {
  3675. color: #9ed2ff;
  3676. margin-bottom: 12px;
  3677. font-size: 13px;
  3678. }
  3679. .feature-property-item {
  3680. padding: 10px 12px;
  3681. margin-bottom: 8px;
  3682. border-radius: 8px;
  3683. background: rgba(61, 132, 205, 0.14);
  3684. border: 1px solid rgba(111, 186, 255, 0.35);
  3685. }
  3686. .feature-property-row {
  3687. display: flex;
  3688. align-items: center;
  3689. gap: 8px;
  3690. margin-bottom: 8px;
  3691. }
  3692. .feature-property-delete-btn {
  3693. flex-shrink: 0;
  3694. }
  3695. .feature-property-footer {
  3696. width: 100%;
  3697. display: flex;
  3698. align-items: center;
  3699. justify-content: space-between;
  3700. }
  3701. .feature-property-actions {
  3702. display: flex;
  3703. align-items: center;
  3704. gap: 12px;
  3705. }
  3706. .feature-property-key-input {
  3707. width: 180px;
  3708. }
  3709. .map-edit-hover-hint {
  3710. position: fixed;
  3711. z-index: 3000;
  3712. pointer-events: none;
  3713. color: #4a4a4a;
  3714. background: #fff;
  3715. border-radius: 4px;
  3716. padding: 7px 10px;
  3717. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.18);
  3718. font-size: 12px;
  3719. line-height: 1.2;
  3720. transform-origin: left top;
  3721. animation: mapHintPop 120ms ease-out;
  3722. }
  3723. @keyframes mapHintPop {
  3724. from {
  3725. transform: scale(0.92);
  3726. opacity: 0.5;
  3727. }
  3728. to {
  3729. transform: scale(1);
  3730. opacity: 1;
  3731. }
  3732. }
  3733. :deep(.feature-property-input .el-input__wrapper) {
  3734. background: rgba(8, 34, 74, 0.68);
  3735. box-shadow: inset 0 0 0 1px rgba(130, 198, 255, 0.4);
  3736. }
  3737. :deep(.feature-property-input .el-input__inner) {
  3738. color: #ffffff;
  3739. }
  3740. :deep(.feature-property-dialog .el-dialog) {
  3741. background: rgba(7, 24, 48, 0.95);
  3742. border: 1px solid rgba(111, 186, 255, 0.5);
  3743. }
  3744. :deep(.feature-property-dialog .el-dialog__title) {
  3745. color: #e8f4ff;
  3746. font-weight: 700;
  3747. }
  3748. :deep(.feature-property-dialog .el-dialog__headerbtn .el-dialog__close) {
  3749. color: #d8ecff;
  3750. }
  3751. :deep(.feature-property-dialog .el-dialog__body) {
  3752. padding-top: 12px;
  3753. }
  3754. :deep(.ace_editor) {
  3755. height: 600px !important;
  3756. max-height: calc(100vh - 300px) !important;
  3757. }
  3758. :deep(.jsoneditor-modes),
  3759. :deep(.jsoneditor-poweredBy) {
  3760. display: none;
  3761. }
  3762. </style>