wujingjing
2025-02-26 948c5662b643593c5d0d50140775affb8791e7fd
src/model/map/OLMap.ts
@@ -2,6 +2,7 @@
import { defaultsDeep } from 'lodash-es';
import type { Overlay } from 'ol';
import { Feature, Map as OpenLayerMap, View } from 'ol';
import type { Extent } from 'ol/extent';
import { extend, getTopLeft, getWidth } from 'ol/extent';
import type { FeatureLike } from 'ol/Feature';
import MVT from 'ol/format/MVT.js';
@@ -29,17 +30,21 @@
import { Logger } from '../logger/Logger';
import { MarkerOverlay } from './overlay/marker';
import { getCurrentPosition } from '/@/utils/brower';
import { travelTree } from '/@/utils/util';
import { ElLoadingService } from 'element-plus';
import { switchMapTheme } from '/@/api/map';
import { formatDate } from '/@/utils/formatTime';
export type LangType = 'zh_cn' | 'en';
export const enum GaoDeSourceType {
   /** @description 默认地图 */
   Default = 0,
   Default = 'default',
   /** @description 影像地图 */
   Satellite = 1,
   Satellite = 'satellite',
   /** @description 矢量地图 */
   Vector = 2,
   Vector = 'standard',
   /** @description 影像路网 */
   SatelliteRoad = 3,
   SatelliteRoad = 'road_network',
}
export const enum OverlayType {
   Marker = 'marker',
@@ -87,6 +92,9 @@
   /** @description 图层控制信息 */
   layerInfo = ref([] as any[]);
   /** @description 图层控制信息 */
   legendList = ref([] as any[]);
   drawStyles = ref([] as any[]);
@@ -231,11 +239,11 @@
      return position;
   }
   async gaodeAddressSearch(address) {
   async gaodeAddressSearch(address, city) {
      this.gaodeApiKey = 'eea6302da02576fe3f3dd3ba1fbe0a04';
      // const url = `https://restapi.amap.com/v3/assistant/inputtips?output=json&city=010&keywords=${address}=${this.gaodeApiKey}`;
      // 搜索 POI
      const url = `https://restapi.amap.com/v3/place/text?keywords=${address}&city=fuzhou&offset=20&page=1&key=${this.gaodeApiKey}&extensions=all `;
      const url = `https://restapi.amap.com/v3/place/text?keywords=${address}&city=${city}&offset=20&page=1&key=${this.gaodeApiKey}&extensions=all `;
      // 搜索 POI 2.0
      // const url = `https://restapi.amap.com/v5/place/text?keywords=${address}&city=beijing&offset=20&page=1&key=${this.gaodeApiKey}&extensions=all
@@ -253,7 +261,6 @@
   }
   drawLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   private isDrawStatus = false;
   removeDrawLayer() {
      if (!this.drawLayer) return;
@@ -341,7 +348,6 @@
            });
            // 添加新的feature
            // this.drawLayer.getSource().addFeature(feature);
            // 添加矩形图层到地图
            this.map.addLayer(this.drawLayer);
@@ -387,7 +393,7 @@
      // 调整视图以适应最小外接矩形
      this.map.getView().fit(extent, {
         maxZoom: 15,
         padding: [50, 50, 50, 50] // 添加内边距使视图更美观
         padding: [50, 50, 50, 50], // 添加内边距使视图更美观
      });
   }
@@ -706,18 +712,23 @@
      return overlay;
   }
   adjustViewToMarkers() {
   getAllMarkerOverlays() {
      const overlays = this.map.getOverlays().getArray();
      const filteredOverlays = overlays.filter((overlay) => {
         const type = overlay.get('type');
         return type === OverlayType.Marker;
      });
      this.adjustViewToOverlays(filteredOverlays);
      return overlays.filter((overlay) => overlay.get('type') === OverlayType.Marker);
   }
   adjustViewToOverlays(overlays: Overlay[]) {
      if (overlays.length === 0) return;
   adjustViewToMarkers() {
      const overlays = this.getAllMarkerOverlays();
      this.adjustViewToOverlays(overlays);
   }
   getAllMarkerOverlaysExtent() {
      const overlays = this.getAllMarkerOverlays();
      const extent = this.getOverlaysExtent(overlays);
      return extent;
   }
   getOverlaysExtent(overlays: Overlay[]) {
      const extent = overlays.reduce<number[] | null>((ext, item) => {
         const coord = item.getPosition();
@@ -726,7 +737,12 @@
         }
         return [Math.min(ext[0], coord[0]), Math.min(ext[1], coord[1]), Math.max(ext[2], coord[0]), Math.max(ext[3], coord[1])];
      }, null);
      return extent;
   }
   adjustViewToOverlays(overlays: Overlay[]) {
      if (overlays.length === 0) return;
      const extent = this.getOverlaysExtent(overlays);
      if (extent) {
         this.fitExtend(extent);
      }
@@ -790,22 +806,21 @@
   }
   zoomToLayers() {
      let extent = this.getAllMarkerOverlaysExtent();
      const layers = this.getAllLayerModels();
      if (!layers || layers.length === 0) return;
      if (layers.length > 0) {
         // 获取所有图层的范围
         extent = layers.reduce((extent, layer) => {
            const layerExtent = layer.getExtent();
      // 获取所有图层的范围
      const extent = layers.reduce((extent, layer) => {
         const layerExtent = layer.getExtent();
            if (!extent) {
               return layerExtent;
            }
         if (!extent) {
            return layerExtent;
         }
         // 合并范围
         return extend(extent, layerExtent);
      }, null);
      if (!extent) return;
            // 合并范围
            return extend(extent, layerExtent);
         }, extent);
      }
      // 聚焦到合并后的范围
      this.map.getView().fit(extent, {
@@ -824,6 +839,189 @@
      }, []);
   }
   setLayerVisible(layerId: string, visible: boolean) {
      const layer = this.getAllLayers().find((item) => item.id === layerId);
      if (layer) {
         layer.isVisible = visible;
      }
   }
   setThemeById(themeId: string) {
      let group;
      let theme;
      travelTree(this.themeInfo.value, (item,index,array,parent) => {
         if (item.type === 'theme' && item.id === themeId) {
            group = parent;
            theme = item;
            return true;
         }
      });
      if (group) {
         group.activeTheme = themeId;
         this.handleThemeChange(themeId, group);
      }
   }
   async changeTheme(ids: string) {
      const loadingInstance = ElLoadingService({
         text: '加载主题中...',
         target: '.layout-parent',
      });
      const res = await switchMapTheme({
         theme_id: ids,
         time: formatDate(new Date()),
      }).finally(() => {
         loadingInstance.close();
      });
      // 加入主题之后的样式函数
      const themeLayerStyleFunc = (feature, resolution) => {
         const otype = feature.get('otype');
         const oname = feature.get('oname');
         // oname 映射样式
         const onameStyleMap = res?.[`O_${otype}`] ?? {};
         const themeStyles = res?.styles ?? [];
         const styleIndex = onameStyleMap[oname]?.style_id;
         const themeStyle = styleIndex == null ? null : themeStyles[styleIndex];
         // if(themeStyle){
         // }
         const shape = feature.getGeometry().getType();
         const styles = [];
         switch (shape) {
            case 'Point':
               const pSize = themeStyle?.PSIZE ?? feature.get('psize');
               const pcolor = themeStyle?.PCOLOR ?? feature.get('pcolor');
               const pStyle = themeStyle?.PSTYLE ?? feature.get('pstyle');
               const pointStyle = this.getPointStyles({
                  size: pSize,
                  color: pcolor,
                  style: pStyle,
               });
               pointStyle && styles.push(pointStyle);
               break;
            case 'LineString':
               const lSize = themeStyle?.LSIZE ?? feature.get('lsize');
               const lColor = themeStyle?.LCOLOR ?? feature.get('lcolor');
               const lStyle = themeStyle?.LSTYLE ?? feature.get('lstyle');
               const pSize1 = themeStyle?.PSIZE ?? feature.get('psize');
               const pcolor1 = themeStyle?.PCOLOR ?? feature.get('pcolor');
               const pStyle1 = themeStyle?.PSTYLE ?? feature.get('pstyle');
               const lineStyle = this.getLineStyles({
                  lsize: lSize,
                  lcolor: lColor,
                  lstyle: lStyle,
                  psize: pSize1,
                  pcolor: pcolor1,
                  pstyle: pStyle1,
               });
               lineStyle && styles.push(...lineStyle);
               break;
            case 'Polygon':
               const pColor = themeStyle?.PCOLOR ?? feature.get('pcolor');
               const lSize1 = themeStyle?.LSIZE ?? feature.get('lsize');
               const lColor1 = themeStyle?.LCOLOR ?? feature.get('lcolor');
               const lstyle1 = themeStyle?.LSTYLE ?? feature.get('lstyle');
               const polygonStyle = this.getPolygonStyles({
                  pcolor: pColor,
                  lsize: lSize1,
                  lcolor: lColor1,
                  lstyle: lstyle1,
               });
               polygonStyle && styles.push(...polygonStyle);
               break;
            default:
               break;
         }
         // switch (otype) {
         //    case 'WDM_JUNCTIONS':
         //       const textStyle = createTextStyle(feature, resolution);
         //       styles.push(textStyle);
         //    case 'WDM_PIPES':
         //       break;
         // }
         //#region ====================== 添加标注 ======================
         const tString = themeStyle?.TSTRING ?? feature.get('tstring');
         const tStringStyle = this.getLabelStyles({
            textContent: tString,
            resolution,
         });
         tStringStyle && styles.push(tStringStyle);
         //#endregion
         return styles;
      };
      const allLayers = this.getAllLayers();
      for (const item of allLayers) {
         if (this.unsupportedLayers.includes(item.id)) {
            continue;
         }
         item.model.setStyle(themeLayerStyleFunc);
      }
      return res?.legends ?? [];
   }
   async handleThemeChange(val?, themeGroup?) {
      const allIds = [];
      for (const item of this.themeInfo.value) {
         if (item.activeTheme) {
            allIds.push(item.activeTheme);
         }
      }
      const ids = allIds.join(',');
      if (!ids) {
         const allLayers = this.getAllLayerModels();
         for (const item of allLayers) {
            const originStyle = item.get('originStyle');
            originStyle && item.setStyle(originStyle);
         }
         return;
      }
      const legends = await this.changeTheme(ids);
      this.legendList.value = this.parseLegends(legends);
   }
   parseLegends(legends) {
      const result = legends.map((item) => {
         const isEqual = item.operate === '=';
         const result = {
            ...item,
            legend: item.legend.map((legendItem, index, array) => {
               const preItem = array[index - 1];
               let label = '';
               if (isEqual) {
                  label = legendItem.value;
               } else if (preItem) {
                  label = `>${preItem.value}且${item.operate}${legendItem.value}`;
               } else {
                  label = `${item.operate}${legendItem.value}`;
               }
               return {
                  ...legendItem,
                  label: label,
               };
            }),
         };
         result.legend.push({
            style: item.default,
            value: '',
            label: result.legend.length == 0 ? '默认' : `>${item.legend[item.legend.length - 1].value}`,
         });
         return result;
      });
      return result;
   }
   /** @description 记录所有图层 */
   setAllLayers(layerModels: Layer[], layers: any[], layerGroup: any[]) {
      this.layerInfo.value = layerGroup.reduce((preVal, curVal) => {