creatMap.vue 18 KB

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