atmCompanytencentMap.vue 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. <template>
  2. <div class="map-page">
  3. <div ref="mapContainer" class="map-container"></div>
  4. <!-- 错误提示 -->
  5. <div v-if="error" class="error-message">{{ error }}</div>
  6. </div>
  7. </template>
  8. <script setup>
  9. import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
  10. import axios from 'axios'
  11. const isMapReady = ref(false)
  12. const mapContainer = ref(null)
  13. const error = ref(null)
  14. const TMap = ref(null);
  15. let activeTempMarker = ref(null)
  16. let infoWindow = ref(null)
  17. let map = null
  18. let markersLayer = null
  19. let soilTypeVectorLayer = null; // 土壤类型多边形图层
  20. let overlay = null
  21. const state = reactive({
  22. showOverlay: false,
  23. showSoilTypes: true,
  24. showSurveyData: true,
  25. shoeWaterSystem: true,
  26. excelData: [], // 用于存储从接口获取的数据
  27. lastTapTime: 0
  28. })
  29. let soilTypeLayer = null
  30. let currentInfoWindow = null;
  31. let surveyDataLayer = ref(null);
  32. let selectedPolygon = ref(null); // 补充定义
  33. const tMapConfig = reactive({
  34. key: import.meta.env.VITE_TMAP_KEY, // 请替换为你的开发者密钥
  35. geocoderURL: 'https://apis.map.qq.com/ws/geocoder/v1/'
  36. })
  37. // 加载SDK的代码保持不变...
  38. const loadSDK = () => {
  39. return new Promise((resolve, reject) => {
  40. if (window.TMap?.service?.Geocoder) {
  41. //console.log('SDK已缓存,直接使用');
  42. TMap.value = window.TMap
  43. return resolve(window.TMap)
  44. }
  45. const script = document.createElement('script')
  46. script.src = `https://map.qq.com/api/gljs?v=2.exp&libraries=basic,service,vector&key=${tMapConfig.key}&callback=initTMap`
  47. window.initTMap = () => {
  48. if (!window.TMap?.service?.Geocoder) {
  49. console.error('SDK加载后仍无效');
  50. reject(new Error('地图SDK加载失败'))
  51. return
  52. }
  53. //console.log('SDK动态加载完毕');
  54. TMap.value = window.TMap
  55. resolve(window.TMap)
  56. }
  57. script.onerror = (err) => {
  58. console.error('SDK加载报错', err);
  59. reject(`地图资源加载失败: ${err.message}`)
  60. document.head.removeChild(script)
  61. }
  62. document.head.appendChild(script)
  63. })
  64. }
  65. // 初始化地图 - 保持大部分不变,增加数据加载
  66. const initMap = async () => {
  67. try {
  68. await loadSDK()
  69. //console.log('开始创建地图实例');
  70. map = new TMap.value.Map(mapContainer.value, {
  71. center: new TMap.value.LatLng(24.39, 114),//前大往下,后大往左
  72. zoom: 9.25,
  73. minZoom: 8,
  74. //maxZoom: 11,
  75. renderOptions: {
  76. antialias: true
  77. },
  78. })
  79. //console.log('地图实例创建成功');
  80. // 创建标记点向量图层
  81. markersLayer = new TMap.value.MultiMarker({
  82. map: map,
  83. zIndex: 1000,
  84. collision:false,
  85. styles: {
  86. default: new TMap.value.MarkerStyle({
  87. width: 30, // 图标宽度
  88. height: 30, // 图标高度
  89. anchor: { x: 12.5, y: 12.5 }, // 居中定位
  90. src: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cG9seWdvbiBwb2ludHM9IjEyLDIgMiwyMCAyMiwyMCIgZmlsbD0iIzFFODhFNSIvPjwvc3ZnPg=='
  91. })
  92. }
  93. });
  94. // 绑定标记点击事件
  95. markersLayer.on('click', handleMarkerClick);
  96. // 创建土壤类型多边形图层
  97. soilTypeVectorLayer = new TMap.value.MultiPolygon({
  98. map: map,
  99. styles: {
  100. default: new TMap.value.PolygonStyle({
  101. fillColor: '#cccccc',
  102. fillOpacity: 0.4,
  103. strokeColor: '#333',
  104. strokeWidth: 1
  105. })
  106. }
  107. });
  108. // 先加载数据,再更新标记
  109. await fetchData(); // 新增:获取数据
  110. if(state.excelData.length > 0) {
  111. const first = state.excelData[0];
  112. // console.log('第一条数据坐标:',
  113. // first.纬度 || first.latitude,
  114. //first.经度 || first.longitude
  115. //);
  116. }
  117. updateMarkers(); // 更新标记点
  118. // 标记地图就绪
  119. isMapReady.value = true;
  120. //console.log('地图初始化完成');
  121. // 创建样式标签并注入样式
  122. const style = document.createElement('style');
  123. style.textContent = `
  124. .water-info-window {
  125. max-width: 80vw !important;
  126. width: auto !important;
  127. overflow: visible !important;
  128. }
  129. .info-value {
  130. white-space: normal !important;
  131. word-wrap: break-word !important;
  132. max-width: none !important;
  133. }
  134. `;
  135. document.head.appendChild(style);
  136. } catch (err) {
  137. isMapReady.value = true;
  138. console.error('initMap执行异常:', err);
  139. error.value = err.message
  140. }
  141. }
  142. // 新增:从接口获取数据
  143. const fetchData = async () => {
  144. try {
  145. const response = await axios.get('http://localhost:3000/table/Atmosphere_company_data', {
  146. timeout: 100000
  147. });
  148. state.excelData = response.data.filter(item => {
  149. if(!item['污染源序号'] || !item.纬度 || !item.经度) { // 替换为新字段
  150. console.warn(`数据不完整,已跳过: ${item.污染源序号 || '未知序号'}`);
  151. return false;
  152. }
  153. const lat = Number(item.纬度);
  154. const lng = Number(item.经度);
  155. const isValid = !isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180;
  156. if(!isValid) console.error(`无效经纬度: ${item.污染源序号} (${item.纬度}, ${item.经度})`);
  157. return isValid;
  158. });
  159. //console.log('有效数据记录:', state.excelData.length);
  160. } catch (err) {
  161. console.error('数据请求失败详情:', err.response?.data || err.message);
  162. error.value = `数据加载失败: ${err.message}`;
  163. }
  164. }
  165. // 更新标记点 - 保持不变
  166. const updateMarkers = () => {
  167. const geometries = state.excelData.map(item => {
  168. //console.log(`ID: ${item.污染源序号}, 坐标: (${item.纬度}, ${item.经度})`); // 替换为新字段
  169. if (!item.污染源序号 || !item.纬度 || !item.经度) return null;
  170. const lat = Number(item.纬度);
  171. const lng = Number(item.经度);
  172. if (isNaN(lat) || isNaN(lng)) return null;
  173. return {
  174. id: item.污染源序号, // 标记 ID 设为「污染源序号」
  175. styleId: 'default',
  176. position: new TMap.value.LatLng(lat, lng),
  177. properties: {
  178. title: item.公司 || `污染源 ${item.污染源序号}`, // 标题用「公司」名称
  179. sampler_id: item.污染源序号,
  180. }
  181. };
  182. });
  183. markersLayer.setGeometries(geometries);
  184. //console.log('成功添加标记点数量:', geometries.length);
  185. };
  186. // Marker点击事件处理 - 保持不变
  187. const handleMarkerClick = async (e) => {
  188. //console.log('点击标记点');
  189. const marker = e.geometry;
  190. if (!marker) {
  191. console.error('未获取到标记点对象');
  192. return;
  193. }
  194. // 关闭之前的信息窗口
  195. if (infoWindow.value) {
  196. infoWindow.value.close();
  197. infoWindow.value = null;
  198. }
  199. // 显示加载中
  200. infoWindow.value = new TMap.value.InfoWindow({
  201. map: map,
  202. position: marker.position,
  203. content: '<div style="padding:12px;text-align:center">加载数据中...</div>',
  204. //offset: { x: 0, y: -220 },
  205. });
  206. infoWindow.value.open();
  207. try {
  208. const markerId = marker.id.trim();
  209. //console.log('点击标记点样品名称:', markerId);
  210. // 直接从本地数据查找,无需二次请求
  211. const matchedData = state.excelData.find(item =>
  212. item.污染源序号.trim() === markerId
  213. );
  214. if (!matchedData) {
  215. console.error("无法匹配的数据列表:", state.excelData.map(i => i.样品名称));
  216. throw new Error(`未找到样品名称为 ${markerId} 的监测数据`);
  217. }
  218. // 创建信息窗口内容
  219. const content = `
  220. <div class="water-info-window">
  221. <h3 class="info-title">${matchedData.公司}</h3>
  222. <div class="info-row">
  223. <span class="info-label">污染源序号:</span>
  224. <span class="info-value">${matchedData.污染源序号}</span>
  225. </div>
  226. <div class="info-row">
  227. <span class="info-label">所属区县:</span>
  228. <span class="info-value">${matchedData.所属区县}</span>
  229. </div>
  230. <div class="info-row">
  231. <span class="info-label">类型:</span>
  232. <span class="info-value">${matchedData.类型}</span>
  233. </div>
  234. <div class="info-row">
  235. <span class="info-label">大气颗粒物排放(t/a):</span>
  236. <span class="info-value">${matchedData['大气颗粒物排放(t/a)']}</span>
  237. </div>
  238. </div>
  239. `;
  240. // 更新信息窗口
  241. infoWindow.value.setContent(content);
  242. } catch (error) {
  243. console.error('API请求失败:', error);
  244. // 显示错误信息
  245. const errorContent = `
  246. <div style="padding:12px;color:red">
  247. <h3>${marker.properties.title}</h3>
  248. <p>获取数据失败: ${error.message}</p>
  249. </div>
  250. `;
  251. infoWindow.value.setContent(errorContent);
  252. }
  253. }
  254. // 其余函数保持不变...
  255. const manageTempMarker = {
  256. add: (lat, lng, phValue) => {
  257. if (activeTempMarker.value) {
  258. markersLayer.remove("-999")
  259. }
  260. // 确保已添加临时样式
  261. if (!markersLayer.getStyles().temp) {
  262. markersLayer.setStyles({
  263. temp: new TMap.value.MarkerStyle({
  264. width: 30,
  265. height: 30,
  266. anchor: { x: 12.5, y: 12.5 },
  267. src: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cG9seWdvbiBwb2ludHM9IjEyLDIgMiwyMCAyMiwyMCIgZmlsbD0iIzFFODhFNSIvPjwvc3ZnPg=='
  268. })
  269. });
  270. }
  271. const tempMarker = markersLayer.add({
  272. id: "-999",
  273. position: new TMap.value.LatLng(lat, lng),
  274. styleId: 'temp',
  275. properties: {
  276. title: '克里金插值',
  277. phValue: parseFloat(phValue).toFixed(2),
  278. isTemp: true
  279. }
  280. })
  281. activeTempMarker.value = tempMarker
  282. },
  283. remove: () => {
  284. if (activeTempMarker.value) {
  285. markersLayer.remove("-999")
  286. activeTempMarker.value = null
  287. }
  288. }
  289. }
  290. onMounted(async () => {
  291. //console.log('开始执行 onMounted');
  292. try {
  293. await initMap()
  294. //console.log('地图初始化完成');
  295. } catch (err) {
  296. console.error('onMounted执行异常', err);
  297. error.value = err.message
  298. }
  299. })
  300. onBeforeUnmount(() => {
  301. if (activeTempMarker.value) {
  302. manageTempMarker.remove()
  303. }
  304. if (markersLayer) markersLayer.setMap(null)
  305. if (overlay) overlay.setMap(null)
  306. if (infoWindow.value) {
  307. infoWindow.value.close()
  308. infoWindow.value = null
  309. }
  310. if (soilTypeVectorLayer) soilTypeVectorLayer.setMap(null)
  311. })
  312. </script>
  313. <style>
  314. /* 原有样式保持不变,新增错误提示样式 */
  315. .error-message {
  316. position: fixed;
  317. top: 20px;
  318. left: 50%;
  319. transform: translateX(-50%);
  320. padding: 12px 20px;
  321. background-color: #ff4444;
  322. color: white;
  323. border-radius: 4px;
  324. z-index: 9999;
  325. box-shadow: 0 2px 8px rgba(0,0,0,0.2);
  326. animation: fadein 0.5s, fadeout 0.5s 4.5s;
  327. }
  328. @keyframes fadein {
  329. from { top: 0; opacity: 0; }
  330. to { top: 20px; opacity: 1; }
  331. }
  332. @keyframes fadeout {
  333. from { top: 20px; opacity: 1; }
  334. to { top: 0; opacity: 0; }
  335. }
  336. /* 其余样式保持不变 */
  337. .map-page {
  338. position: relative;
  339. width: 100vw;
  340. height: 100vh;
  341. }
  342. .map-container {
  343. width: 100%;
  344. height: 100vh ;
  345. min-height: 600px;
  346. pointer-events: all;
  347. }
  348. .water-info-window {
  349. max-width: 80vw; /* 相对视口最大值,更加灵活 */
  350. width: auto;
  351. padding: 16px;
  352. border-radius: 12px;
  353. box-shadow: 0 6px 18px rgba(0,0,0,0.15);
  354. background: #fff;
  355. border: 1px solid #e5e7eb;
  356. overflow: visible; /* 配合自动平移,确保内容不被裁剪 */
  357. }
  358. /* 标题区:增加渐变装饰线 */
  359. .info-title {
  360. font-size: 18px;
  361. font-weight: 600;
  362. color: #1e3a8a;
  363. text-align: center;
  364. margin-bottom: 14px;
  365. padding-bottom: 12px;
  366. border-bottom: 1px solid #e5e7eb;
  367. position: relative; /* 为伪元素准备 */
  368. }
  369. .info-title::after {
  370. content: "";
  371. position: absolute;
  372. bottom: 0;
  373. left: 20px;
  374. right: 20px;
  375. height: 1px;
  376. background: linear-gradient(to right,
  377. rgba(30, 58, 138, 0.1),
  378. rgba(30, 58, 138, 0.2),
  379. rgba(30, 58, 138, 0.1)
  380. );
  381. }
  382. /* 数据行:Grid 布局确保对齐 */
  383. .info-row {
  384. display: grid;
  385. grid-template-columns: 180px 1fr; /* 标签180px,值自适应 */
  386. gap: 12px; /* 列间距 */
  387. align-items: flex-start;
  388. margin: 10px 0;
  389. margin: 10px 0;/**增加行间距,提升可读性 */
  390. }
  391. /* 标签:右对齐 + 深灰配色 */
  392. .info-label {
  393. text-align: right;
  394. color: #6b7280;
  395. font-size: 14px;
  396. }
  397. /* 数据值:浅灰背景 + 智能换行 */
  398. .info-value {
  399. padding: 6px 10px;
  400. background: #f3f4f6;
  401. border-radius: 6px;
  402. font-size: 14px;
  403. white-space: normal; /* 长文本强制换行 */
  404. word-wrap: break-word;
  405. overflow: visible;/**不隐藏溢出内容 */
  406. text-overflow: clip;
  407. min-height: 24px; /* 确保最小高度,避免内容塌陷 */
  408. }
  409. /* 响应式适配(小窗口自动压缩) */
  410. @media (max-width: 480px) {
  411. .water-info-window {
  412. max-width: 90vw; /* 占满视口宽度 */
  413. padding: 10px;
  414. }
  415. .info-row {
  416. grid-template-columns: 100px 1fr; /* 缩小标签宽度 */
  417. }
  418. }
  419. </style>