Kaynağa Gözat

refactor: 抽离坐标转换功能到独立工具类

- 从TongzhouTrafficMap.vue组件中完全移除坐标转换相关代码
- 创建src/utils/coordConverter.js工具类,提供百度地图坐标转高德地图坐标功能
- 新增map_data_baidu.json文件,保存原始百度地图坐标数据
- 保留map_data_gaode.json文件,保存转换后的高德地图坐标数据
- 简化TongzhouTrafficMap组件,使其只负责地图显示,不处理坐标转换
- 工具类提供独立的convertBaiduToGaode和saveDataToJson方法,方便需要时调用
sequoia tungfang 1 ay önce
ebeveyn
işleme
b3158137dc

+ 4 - 98
src/components/TongzhouTrafficMap.vue

@@ -159,7 +159,7 @@ export default {
     // 动态加载地图数据
     async loadMapData() {
       try {
-        const mapDataModule = await import('@/mock/map_data.json');
+        const mapDataModule = await import('@/mock/map_data_gaode.json');
         this.intersectionData = mapDataModule.default || [];
         console.log('地图数据加载成功,共', this.intersectionData.length, '个路口');
       } catch (error) {
@@ -168,96 +168,6 @@ export default {
       }
     },
 
-    // 将百度地图坐标转换为高德地图坐标
-    async convertBaiduToGaode() {
-      if (!this.AMap || !this.AMap.convertFrom) {
-        console.warn('AMap.ConvertFrom 插件未加载,跳过坐标转换');
-        return;
-      }
-
-      console.log('开始转换百度地图坐标为高德地图坐标...');
-      
-      // 批量转换,每次最多50个坐标,减少请求频率
-      const batchSize = 50;
-      const total = this.intersectionData.length;
-      
-      for (let i = 0; i < total; i += batchSize) {
-        const batch = this.intersectionData.slice(i, i + batchSize);
-        const baiduCoords = batch.map(item => [
-          item["位置-经度"],
-          item["位置-纬度"]
-        ]);
-
-        try {
-          const result = await new Promise((resolve, reject) => {
-            this.AMap.convertFrom(baiduCoords, 'baidu', function(status, result) {
-              if (status === 'complete') {
-                resolve(result);
-              } else {
-                reject(new Error('坐标转换失败: ' + JSON.stringify(result)));
-              }
-            });
-          });
-
-          // 更新转换后的坐标
-          if (result.locations) {
-            result.locations.forEach((location, index) => {
-              if (batch[index]) {
-                batch[index]["位置-经度"] = location.lng;
-                batch[index]["位置-纬度"] = location.lat;
-              }
-            });
-          }
-
-          console.log(`已转换 ${Math.min(i + batchSize, total)} / ${total} 个坐标`);
-        } catch (error) {
-          console.error('坐标转换失败:', error);
-          
-          // 如果是频率限制错误,等待更长时间后重试
-          if (error.message.includes('CUQPS_HAS_EXCEEDED_THE_LIMIT')) {
-            console.log('遇到频率限制,等待5秒后重试...');
-            await new Promise(resolve => setTimeout(resolve, 5000));
-            // 重试当前批次
-            i -= batchSize;
-            continue;
-          }
-        }
-
-        // 避免请求过于频繁,增加等待时间
-        if (i + batchSize < total) {
-          await new Promise(resolve => setTimeout(resolve, 2000));
-        }
-      }
-
-      console.log('坐标转换完成');
-      
-      // 保存转换后的坐标到新文件
-      this.saveConvertedData();
-    },
-
-    // 保存转换后的坐标到新文件
-    saveConvertedData() {
-      try {
-        // 在浏览器环境中,我们可以通过下载的方式保存文件
-        const dataStr = JSON.stringify(this.intersectionData, null, 2);
-        const dataBlob = new Blob([dataStr], { type: 'application/json' });
-        
-        const url = URL.createObjectURL(dataBlob);
-        const link = document.createElement('a');
-        link.href = url;
-        link.download = 'map_data_gaode.json';
-        link.click();
-        
-        URL.revokeObjectURL(url);
-        console.log('转换后的坐标数据已下载为 map_data_gaode.json');
-        
-        // 同时,我们可以提示用户手动将文件保存到 src/mock 目录
-        console.log('请将下载的 map_data_gaode.json 文件保存到 src/mock 目录');
-      } catch (error) {
-        console.error('保存转换后的数据失败:', error);
-      }
-    },
-
     // 检查地图环境是否安全可用
     isMapReady() {
       return !this._isDestroyed && this.map && typeof this.map.add === 'function';
@@ -329,10 +239,11 @@ export default {
 
       window._AMapSecurityConfig = { securityJsCode: this.securityJsCode };
       try {
+        // 固定加载需要的插件
         const AMap = await AMapLoader.load({
           key: this.amapKey,
           version: "2.0",
-          plugins: ['AMap.Driving', 'AMap.ConvertFrom']
+          plugins: ['AMap.Driving']
         });
 
         // 异步回来后,首先检查组件是否还在
@@ -346,12 +257,7 @@ export default {
         });
 
         this.map.on('complete', () => {
-          if (!this._isDestroyed) {
-            // 先转换坐标,再绘制路线
-            this.convertBaiduToGaode().then(() => {
-              this.drawStaticRoutes();
-            });
-          }
+          if (!this._isDestroyed) this.drawStaticRoutes();
         });
       } catch (err) {
         console.error('地图加载失败:', err);

src/mock/map_data.json → src/mock/map_data_baidu.json


Dosya farkı çok büyük olduğundan ihmal edildi
+ 7466 - 1
src/mock/map_data_gaode.json


+ 101 - 0
src/utils/coordConverter.js

@@ -0,0 +1,101 @@
+/**
+ * 坐标转换工具类
+ * 提供百度地图坐标(BD09)到高德地图坐标(GCJ02)的转换功能
+ */
+
+/**
+ * 批量转换百度地图坐标为高德地图坐标
+ * @param {Array} data - 包含百度地图坐标的数据数组,每个元素应包含"位置-经度"和"位置-纬度"字段
+ * @param {Object} AMap - 高德地图API实例
+ * @returns {Promise<Array>} 转换后的坐标数据数组
+ */
+export async function convertBaiduToGaode(data, AMap) {
+  if (!AMap || !AMap.convertFrom) {
+    console.warn('AMap.ConvertFrom 插件未加载,跳过坐标转换');
+    return data;
+  }
+
+  console.log('开始转换百度地图坐标为高德地图坐标...');
+  
+  // 批量转换,每次最多50个坐标,减少请求频率
+  const batchSize = 50;
+  const total = data.length;
+  
+  for (let i = 0; i < total; i += batchSize) {
+    const batch = data.slice(i, i + batchSize);
+    const baiduCoords = batch.map(item => [
+      item["位置-经度"],
+      item["位置-纬度"]
+    ]);
+
+    try {
+      const result = await new Promise((resolve, reject) => {
+        AMap.convertFrom(baiduCoords, 'baidu', function(status, result) {
+          if (status === 'complete') {
+            resolve(result);
+          } else {
+            reject(new Error('坐标转换失败: ' + JSON.stringify(result)));
+          }
+        });
+      });
+
+      // 更新转换后的坐标
+      if (result.locations) {
+        result.locations.forEach((location, index) => {
+          if (batch[index]) {
+            batch[index]["位置-经度"] = location.lng;
+            batch[index]["位置-纬度"] = location.lat;
+          }
+        });
+      }
+
+      console.log(`已转换 ${Math.min(i + batchSize, total)} / ${total} 个坐标`);
+    } catch (error) {
+      console.error('坐标转换失败:', error);
+      
+      // 如果是频率限制错误,等待更长时间后重试
+      if (error.message.includes('CUQPS_HAS_EXCEEDED_THE_LIMIT')) {
+        console.log('遇到频率限制,等待5秒后重试...');
+        await new Promise(resolve => setTimeout(resolve, 5000));
+        // 重试当前批次
+        i -= batchSize;
+        continue;
+      }
+    }
+
+    // 避免请求过于频繁,增加等待时间
+    if (i + batchSize < total) {
+      await new Promise(resolve => setTimeout(resolve, 2000));
+    }
+  }
+
+  console.log('坐标转换完成');
+  return data;
+}
+
+/**
+ * 保存数据到JSON文件(浏览器下载)
+ * @param {Array} data - 要保存的数据
+ * @param {string} filename - 文件名,默认为"map_data_gaode.json"
+ */
+export function saveDataToJson(data, filename = 'map_data_gaode.json') {
+  try {
+    // 在浏览器环境中,我们可以通过下载的方式保存文件
+    const dataStr = JSON.stringify(data, null, 2);
+    const dataBlob = new Blob([dataStr], { type: 'application/json' });
+    
+    const url = URL.createObjectURL(dataBlob);
+    const link = document.createElement('a');
+    link.href = url;
+    link.download = filename;
+    link.click();
+    
+    URL.revokeObjectURL(url);
+    console.log(`数据已下载为 ${filename}`);
+    
+    // 同时,我们可以提示用户手动将文件保存到 src/mock 目录
+    console.log('请将下载的文件保存到 src/mock 目录');
+  } catch (error) {
+    console.error('保存数据失败:', error);
+  }
+}