creatMap.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. <template>
  2. <el-dialog
  3. v-model="visible"
  4. title="选择地图位置"
  5. width="1200px"
  6. :before-close="handleClose"
  7. destroy-on-close
  8. class="map-fire-dialog"
  9. >
  10. <div class="map-dialog-content">
  11. <!-- 搜索框 -->
  12. <div id="panel" class="scrollbar1">
  13. <div id="searchBar">
  14. <el-select class="search-select" v-model="selectedSearchAdress" placeholder="地址">
  15. <el-option label="地址" value="1"></el-option>
  16. <el-option label="经纬度" value="2"></el-option>
  17. </el-select>
  18. <input class="search-input-latlng" v-if="selectedSearchAdress === '2'" @input="handleSearch" autocomplete="off" @keydown="handleKeyDown" placeholder="输入经纬度搜索,如23.117661,113.281272" />
  19. <input class="search-input-address" v-else id="searchInput" @input="handleSearch" autocomplete="off" placeholder="输入地址搜索" />
  20. <!-- <input id="searchInput" @input="handleSearch" autocomplete="off" @keydown="handleKeyDown" :placeholder="selectedSearchAdress === '1' ? '输入地址' : '输入经纬度'" /> -->
  21. </div>
  22. <div id="searchResults">暂无数据</div>
  23. </div>
  24. <!-- 地图容器 -->
  25. <div class="map-container" v-if="visible">
  26. <div id="container" class="map" style="width: 800px; height: 600px" tabindex="0"></div>
  27. </div>
  28. </div>
  29. <template #footer>
  30. <div class="dialog-footer">
  31. <el-button @click="handleClose">取消</el-button>
  32. <el-button type="primary" @click="handleConfirm">
  33. 确定
  34. </el-button>
  35. </div>
  36. </template>
  37. </el-dialog>
  38. </template>
  39. <script setup lang="ts">
  40. import { ref, watch, nextTick, onUnmounted, onMounted } from 'vue'
  41. import { ElDialog, ElInput, ElButton, ElDescriptions, ElDescriptionsItem, ElIcon, ElMessage } from 'element-plus'
  42. import { Search } from '@element-plus/icons-vue'
  43. import AMapLoader from '@amap/amap-jsapi-loader'
  44. import html2canvas from 'html2canvas'
  45. import { uploadFileToServer, canvasToBlob, blobToFile } from '@/util/upload-utils'
  46. import { axios } from '@/request'
  47. import { addOrUpdateCaseTabulation } from '@/request/urls'
  48. import { user } from "@/store/user";
  49. // 添加高德地图类型声明
  50. declare const AMap: any
  51. declare const AMapUI: any
  52. // 定义组件props和emits
  53. interface Props {
  54. modelValue: boolean
  55. caseId?: string | number
  56. }
  57. interface LocationInfo {
  58. name?: string
  59. address?: string
  60. lat?: number
  61. lng?: number
  62. adcode?: string
  63. citycode?: string
  64. district?: string
  65. screenshotUrl?: string
  66. screenshotFileName?: string
  67. }
  68. const props = defineProps<Props>()
  69. const mapInput = ref('')
  70. const emit = defineEmits<{
  71. 'update:modelValue': [value: boolean]
  72. 'confirm': [location: any]
  73. }>()
  74. // 响应式变量
  75. const visible = ref(false)
  76. const keyword = ref('')
  77. const selectedLocation = ref<LocationInfo | null>(null)
  78. const mapContainer = ref<HTMLDivElement>()
  79. // 高德地图相关变量
  80. let map: any = null
  81. let placeSearch: any = null
  82. let geocoder: any = null
  83. let currentMarker: any = null
  84. let poiPicker: any = null
  85. // 高德地图配置
  86. const AMAP_KEY = '2ae5a7713612a8d5a65cfd54c989c969'
  87. const selectedSearchAdress = ref('1')
  88. const searchInputValue = ref('')
  89. // 根基app打开不同地址
  90. const appId = import.meta.env.VITE_APP_APP || 'fire'
  91. const url = import.meta.env.VITE_DRAW_URL || 'http://mix3d.4dkankan.com'
  92. // 防抖定时器
  93. let searchDebounceTimer: number | null = null
  94. // 监听visible变化
  95. watch(() => props.modelValue, (newVal) => {
  96. visible.value = newVal
  97. if (newVal) {
  98. nextTick(() => {
  99. initMap()
  100. })
  101. }
  102. }, { immediate: true })
  103. watch(visible, (newVal) => {
  104. selectedSearchAdress.value = '1'
  105. emit('update:modelValue', newVal)
  106. })
  107. // 监听搜索类型变化,切换时清空输入框和重置搜索
  108. watch(selectedSearchAdress, (newVal, oldVal) => {
  109. if (newVal !== oldVal) {
  110. // 清空输入框
  111. searchInputValue.value = ''
  112. const searchInput = document.getElementById('searchInput') as HTMLInputElement
  113. if (searchInput) {
  114. searchInput.value = ''
  115. }
  116. // 重置搜索结果
  117. const searchResults = document.getElementById('searchResults')
  118. if (searchResults) {
  119. searchResults.innerHTML = '暂无数据'
  120. }
  121. // 清空地图标记
  122. // if (map) {
  123. // map.clearMap()
  124. // }
  125. // 根据搜索类型调整POI选择器的显示
  126. if (poiPicker) {
  127. if (newVal === '2') {
  128. // 经纬度搜索模式,隐藏选择列表
  129. poiPicker.hideSearchResults()
  130. } else {
  131. // 地址搜索模式,可以显示选择列表
  132. poiPicker.searchByKeyword('')
  133. }
  134. }
  135. }
  136. })
  137. // 初始化地图
  138. const initMap = async () => {
  139. map = new AMap.Map('container', {
  140. zoom: 11,
  141. key: AMAP_KEY, // 替换为你的API密钥
  142. center: [116.397513, 39.908739],
  143. WebGLParams: {
  144. preserveDrawingBuffer: true
  145. }
  146. });
  147. AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {
  148. poiPicker = new PoiPicker({
  149. input: 'searchInput',
  150. placeSearchOptions: {
  151. map: map,
  152. pageSize: 7,
  153. pageIndex: 1,
  154. },
  155. searchResultsContainer: 'searchResults'
  156. });
  157. poiPicker.on('poiPicked', function(poiResult) {
  158. selectedLocation.value = poiResult.item;//选中的信息
  159. poiPicker.hideSearchResults();
  160. // map.clearMap();
  161. var source = poiResult.source, poi = poiResult.item;
  162. if (source !== 'search') {
  163. //suggest来源的,同样调用搜索
  164. poiPicker.searchByKeyword(poi.name);
  165. } else {
  166. // 舒琪说不需要marker
  167. // addMarker(poi.location.lng, poi.location.lat)
  168. // console.log(poi);
  169. }
  170. });
  171. poiPicker.onCityReady(function() {
  172. poiPicker.searchByKeyword('');
  173. });
  174. });
  175. }
  176. const handleKeyDown = (e: KeyboardEvent) => {
  177. if (e.key === 'Enter') {
  178. if(selectedSearchAdress.value === '2'){
  179. console.log(11111)
  180. e.preventDefault()
  181. e.stopPropagation()
  182. return
  183. }
  184. }
  185. }
  186. // 验证经纬度格式的函数
  187. const validateCoordinates = (input: string): { isValid: boolean; lat?: number; lng?: number } => {
  188. // 移除空格
  189. const trimmed = input.trim()
  190. // 检查是否包含逗号
  191. if (!trimmed.includes(',')) {
  192. return { isValid: false }
  193. }
  194. // 分割经纬度
  195. const parts = trimmed.split(',')
  196. if (parts.length !== 2) {
  197. return { isValid: false }
  198. }
  199. // 转换为数字并验证
  200. const lat = parseFloat(parts[0].trim())
  201. const lng = parseFloat(parts[1].trim())
  202. // 验证是否为有效数字
  203. if (isNaN(lat) || isNaN(lng)) {
  204. return { isValid: false }
  205. }
  206. // 验证纬度范围 (-90 到 90)
  207. if (lat < -90 || lat > 90) {
  208. return { isValid: false }
  209. }
  210. // 验证经度范围 (-180 到 180)
  211. if (lng < -180 || lng > 180) {
  212. return { isValid: false }
  213. }
  214. return { isValid: true, lat, lng }
  215. }
  216. // 根据经纬度定位地图
  217. const locateByCoordinates = (lat: number, lng: number) => {
  218. if (!map) {
  219. ElMessage.error('地图未初始化')
  220. return
  221. }
  222. try {
  223. // 创建经纬度点
  224. const lngLat = new AMap.LngLat(lng, lat)
  225. // 设置地图中心点并调整缩放级别
  226. map.setZoomAndCenter(15, lngLat)
  227. // 清除之前的标记
  228. // map.clearMap()
  229. // 添加标记
  230. const marker = new AMap.Marker({
  231. position: lngLat,
  232. content: '<div class="amap_lib_placeSearch_poi"></div>',
  233. offset: new AMap.Pixel(-10, -31)
  234. })
  235. map.add(marker)
  236. // 清空搜索结果显示
  237. const searchResults = document.getElementById('searchResults')
  238. if (searchResults) {
  239. searchResults.innerHTML = `
  240. <div style="padding: 16px; text-align: center; color: #606266;width:345px;height: 106px;border: 1px solid #D9D9D9;">
  241. <div style="font-weight: 500; margin-bottom: 8px;color:#67C23A;">经纬度定位成功</div>
  242. <div style="font-size: 14px;color: #A7A7A7;">
  243. 纬度: ${lat}<br/>
  244. 经度: ${lng}
  245. </div>
  246. </div>
  247. `
  248. }
  249. ElMessage.success('经纬度定位成功')
  250. } catch (error) {
  251. console.error('经纬度定位失败:', error)
  252. ElMessage.error('经纬度定位失败')
  253. }
  254. }
  255. // 清除防抖定时器
  256. const clearSearchDebounce = () => {
  257. if (searchDebounceTimer) {
  258. clearTimeout(searchDebounceTimer)
  259. searchDebounceTimer = null
  260. }
  261. }
  262. // 防抖搜索函数
  263. const debouncedSearch = (inputValue: string, searchType: string) => {
  264. clearSearchDebounce()
  265. searchDebounceTimer = setTimeout(() => {
  266. if (searchType === '2') {
  267. // 经纬度搜索
  268. if (!inputValue.trim()) {
  269. // 输入为空时,清空搜索结果
  270. const searchResults = document.getElementById('searchResults')
  271. if (searchResults) {
  272. searchResults.innerHTML = '暂无数据'
  273. }
  274. return
  275. }
  276. const validation = validateCoordinates(inputValue)
  277. if (validation.isValid && validation.lat !== undefined && validation.lng !== undefined) {
  278. // 经纬度格式正确,进行定位
  279. locateByCoordinates(validation.lat, validation.lng)
  280. } else {
  281. // 经纬度格式错误,只在搜索结果区域显示提示,不弹窗
  282. const searchResults = document.getElementById('searchResults')
  283. if (searchResults) {
  284. searchResults.innerHTML = `
  285. <div style="padding: 16px; text-align: center; width:345px;height: 106px;border: 1px solid #D9D9D9;">
  286. <div style="font-weight: 600; margin-bottom: 8px;color: #B3261E;">经纬度格式错误</div>
  287. <div style="font-size: 12px; line-height: 1.5;color:#A7A7A7;">
  288. 请输入正确的经纬度格式:<br/>
  289. 纬度,经度(例如:23.11766,113.28122)<br/>
  290. 纬度范围:-90 到 90<br/>
  291. 经度范围:-180 到 180
  292. </div>
  293. </div>
  294. `
  295. }
  296. }
  297. } else {
  298. console.log(22222)
  299. // 地址搜索,保持原有逻辑
  300. if (poiPicker) {
  301. poiPicker.placeSearch.opt.pageIndex = 1;
  302. poiPicker.searchByKeyword(inputValue)
  303. }
  304. }
  305. }, 500) // 500ms防抖延迟
  306. }
  307. const handleSearch = (e) => {
  308. console.log('handleSearch', e.target.value)
  309. const inputValue = e.target.value
  310. searchInputValue.value = inputValue
  311. // 对于经纬度搜索,强制隐藏POI选择列表
  312. if (selectedSearchAdress.value === '2' && poiPicker) {
  313. poiPicker.hideSearchResults()
  314. }
  315. // 使用防抖搜索
  316. debouncedSearch(inputValue, selectedSearchAdress.value)
  317. }
  318. // 添加标记
  319. const addMarker = (lng: number, lat: number) => {
  320. // 添加新标记
  321. var marker = new AMap.Marker({
  322. position: new AMap.LngLat(lng, lat),
  323. content: '<div class="amap_lib_placeSearch_poi"></div>',
  324. offset: new AMap.Pixel(-10, -31)
  325. });
  326. map.add(marker)
  327. }
  328. // 处理弹窗关闭
  329. const handleClose = () => {
  330. visible.value = false
  331. selectedLocation.value = null
  332. keyword.value = ''
  333. // 清理地图
  334. if (map) {
  335. map.destroy()
  336. map = null
  337. }
  338. }
  339. const getMapSize = () => {
  340. if (!map) {
  341. ElMessage.error('地图未初始化')
  342. return
  343. }
  344. try {
  345. // 获取当前地图的可视区域边界
  346. const bounds = map.getBounds()
  347. const southwest = bounds.getSouthWest() // 西南角
  348. const northeast = bounds.getNorthEast() // 东北角
  349. const northwest = new (window as any).AMap.LngLat(southwest.lng, northeast.lat) // 西北角
  350. const southeast = new (window as any).AMap.LngLat(northeast.lng, southwest.lat) // 东南角
  351. // 使用高德地图的几何工具计算距离(单位:米)
  352. const AMap = (window as any).AMap
  353. // 计算宽度(东西方向距离)
  354. const width = AMap.GeometryUtil.distance(southwest, southeast)
  355. // 计算高度(南北方向距离)
  356. const height = AMap.GeometryUtil.distance(southwest, northwest)
  357. // 计算面积(平方米)
  358. const area = width * height
  359. // 获取当前缩放级别
  360. const zoom = map.getZoom()
  361. // 获取地图中心点
  362. const center = map.getCenter()
  363. const viewportInfo = {
  364. width: width, // 宽度(米)
  365. height: height, // 高度(米)
  366. area: Math.round(area), // 面积(平方米)
  367. zoom: zoom, // 缩放级别
  368. center: {
  369. lat: center.lat,
  370. lng: center.lng
  371. },
  372. bounds: {
  373. southwest: { lat: southwest.lat, lng: southwest.lng },
  374. northeast: { lat: northeast.lat, lng: northeast.lng }
  375. }
  376. }
  377. console.log('当前可视区域信息:', viewportInfo)
  378. // ElMessage.success(`
  379. // 可视区域信息:
  380. // 宽度:${viewportInfo.width.toLocaleString()} 米
  381. // 高度:${viewportInfo.height.toLocaleString()} 米
  382. // 面积:${viewportInfo.area.toLocaleString()} 平方米
  383. // 缩放级别:${viewportInfo.zoom.toFixed(2)}
  384. // `)
  385. return {
  386. width: viewportInfo.width,
  387. height: viewportInfo.height,
  388. }
  389. } catch (error) {
  390. console.error('计算可视区域失败:', error)
  391. ElMessage.error('计算可视区域失败')
  392. }
  393. }
  394. const getCanvasImage = async (): Promise<{url: string, fileName: string} | null> => {
  395. try {
  396. // 使用html2canvas截图高德地图可视化区域
  397. const mapElement = document.getElementById('container')
  398. if (!mapElement) {
  399. ElMessage.error('地图容器未找到')
  400. return null
  401. }
  402. // ElMessage.info('正在生成地图截图...')
  403. // 配置html2canvas选项
  404. const canvas = await html2canvas(mapElement, {
  405. useCORS: true,
  406. allowTaint: true,
  407. scale: 1,
  408. logging: false,
  409. imageTimeout: 15000,
  410. // 忽略某些元素(比如控件)
  411. ignoreElements: (element) => {
  412. return element.classList.contains('amap-logo') ||
  413. element.classList.contains('amap-copyright') ||
  414. element.classList.contains('amap-controls')
  415. }
  416. })
  417. // 将canvas转换为Blob
  418. const blob = await canvasToBlob(canvas, 0.8, 'image/jpeg')
  419. // 生成文件名
  420. const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  421. const fileName = `map-screenshot-${timestamp}.jpg`
  422. // 转换为File对象
  423. const file = blobToFile(blob, fileName)
  424. // 上传文件
  425. const uploadResult = await uploadFileToServer(file, (progressEvent) => {
  426. // 可选:显示上传进度
  427. if (progressEvent.lengthComputable) {
  428. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
  429. console.log(`上传进度: ${percentCompleted}%`)
  430. }
  431. })
  432. console.log('上传成功:', uploadResult)
  433. return uploadResult
  434. } catch (error) {
  435. console.error('截图或上传失败:', error)
  436. ElMessage.error('截图或上传失败,请重试')
  437. return null
  438. }
  439. }
  440. // 处理确认选择
  441. const handleConfirm = async () => {
  442. try {
  443. emit('confirm', selectedLocation.value)
  444. handleClose()
  445. } catch (error) {
  446. console.error('保存方位图失败:', error)
  447. // ElMessage.error('保存方位图失败,请重试')
  448. }
  449. }
  450. // 组件卸载时清理
  451. onUnmounted(() => {
  452. if (map) {
  453. map.destroy()
  454. }
  455. // 清除防抖定时器
  456. clearSearchDebounce()
  457. })
  458. </script>
  459. <style lang="scss">
  460. .map-fire-dialog{
  461. .el-dialog__header{
  462. text-align: left;
  463. border-bottom: 1px solid #dcdfe6;
  464. margin-bottom: 16px;
  465. }
  466. // https://a.amap.com/jsapi/static/image/plugin/marker_red.png
  467. // .amap-marker{
  468. // display: none!important;
  469. // }
  470. .amap-info-contentContainer{
  471. display: none!important;
  472. }
  473. }
  474. </style>
  475. <style scoped lang="scss">
  476. .map-dialog-content {
  477. height: 600px;
  478. display: flex;
  479. // flex-direction: column;
  480. }
  481. #panel {
  482. // position: absolute;
  483. // top: 24px;
  484. // left: 24px;
  485. height: 100%;
  486. overflow: auto;
  487. width: 400px;
  488. padding-right: 16px;
  489. // z-index: 999;
  490. background: #fff;
  491. :deep(.amap-ui-poi-picker-sugg-container) {
  492. display: none;
  493. }
  494. #searchBar{
  495. display: flex;
  496. width: 380px;
  497. text-align: left;
  498. margin-bottom: 16px;
  499. }
  500. .search-select{
  501. width: 100px;
  502. height: 40px!important;
  503. :deep(.el-select__wrapper){
  504. border-radius: 4px 0 0 4px;
  505. height: 40px;
  506. }
  507. }
  508. .search-input-latlng{
  509. width: 260px;
  510. height: 38px;
  511. border-radius: 0 4px 4px 0;
  512. border: 1px solid #dcdfe6;
  513. border-left: 0;
  514. padding: 0 10px;
  515. font-size: 14px;
  516. color: #303133;
  517. background: #fff;
  518. outline: none;
  519. }
  520. :deep(#searchInput) {
  521. width: 260px;
  522. height: 38px;
  523. border-radius: 0 4px 4px 0;
  524. border: 1px solid #dcdfe6;
  525. border-left: 0;
  526. padding: 0 10px;
  527. font-size: 14px;
  528. color: #303133;
  529. background: #fff;
  530. outline: none;
  531. }
  532. }
  533. #searchResults {
  534. display: flex;
  535. justify-content: center;
  536. align-items: center;
  537. width: 100%;
  538. height: 540px;
  539. overflow: auto;
  540. }
  541. .search-section {
  542. position: relative;
  543. margin-bottom: 16px;
  544. z-index: 1000;
  545. }
  546. .search-results {
  547. position: absolute;
  548. top: 100%;
  549. left: 0;
  550. right: 0;
  551. background: white;
  552. border: 1px solid #dcdfe6;
  553. border-top: none;
  554. border-radius: 0 0 4px 4px;
  555. max-height: 200px;
  556. overflow-y: auto;
  557. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  558. }
  559. .search-item {
  560. padding: 12px 16px;
  561. cursor: pointer;
  562. border-bottom: 1px solid #f0f0f0;
  563. transition: background-color 0.2s;
  564. &:hover {
  565. background-color: #f5f7fa;
  566. }
  567. &:last-child {
  568. border-bottom: none;
  569. }
  570. }
  571. .item-name {
  572. font-weight: 500;
  573. color: #303133;
  574. margin-bottom: 4px;
  575. }
  576. .item-address {
  577. font-size: 12px;
  578. color: #909399;
  579. }
  580. .map-container {
  581. width: 800px;
  582. height: 600px;
  583. position: relative;
  584. border: 1px solid #dcdfe6;
  585. border-radius: 4px;
  586. overflow: hidden;
  587. }
  588. .amap-wrapper {
  589. width: 100%;
  590. height: 100%;
  591. }
  592. .location-info {
  593. margin-top: 16px;
  594. }
  595. .dialog-footer {
  596. display: flex;
  597. justify-content: flex-end;
  598. gap: 12px;
  599. }
  600. // 覆盖高德地图控件样式
  601. :deep(.amap-logo) {
  602. display: none !important;
  603. }
  604. :deep(.amap-copyright) {
  605. display: none !important;
  606. }
  607. </style>