wujingjing
2025-02-26 08c6ecf506bfc7003894775fe57d98d9b11f3d9e
src/model/map/OLMap.ts
@@ -1,12 +1,16 @@
import axios from 'axios';
import { defaultsDeep } from 'lodash-es';
import type { Feature, Overlay } from 'ol';
import { Map as OpenLayerMap, View } from 'ol';
import type { Overlay } from 'ol';
import { Feature, Map as OpenLayerMap, View } from 'ol';
import type { Extent } from 'ol/extent';
import { getTopLeft, getWidth } from 'ol/extent';
import { extend, getTopLeft, getWidth } from 'ol/extent';
import type { FeatureLike } from 'ol/Feature';
import MVT from 'ol/format/MVT.js';
import WKT from 'ol/format/WKT';
import { Point } from 'ol/geom';
import type Geometry from 'ol/geom/Geometry';
import { defaults as olDefaults } from 'ol/interaction';
import { Draw, defaults as olDefaults } from 'ol/interaction';
import { createBox } from 'ol/interaction/Draw';
import type Layer from 'ol/layer/Layer';
import Tile from 'ol/layer/Tile';
import VectorLayer from 'ol/layer/Vector';
@@ -23,8 +27,13 @@
import type { ViewOptions } from 'ol/View';
import type { Ref, ShallowRef } from 'vue';
import { markRaw, ref } from 'vue';
import { MarkerOverlay } from './overlay/marker';
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 {
@@ -84,6 +93,9 @@
   /** @description 图层控制信息 */
   layerInfo = ref([] as any[]);
   /** @description 图层控制信息 */
   legendList = ref([] as any[]);
   drawStyles = ref([] as any[]);
   /** @description 主题信息 */
@@ -91,7 +103,7 @@
   activeSourceType: Ref<GaoDeSourceType> = ref(GaoDeSourceType.Vector);
   interactLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   searchHighlightLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   /** @description 当前激活状态 feature */
   activeFeature: ShallowRef<FeatureLike> = ref(null);
   private emit(eventName: OLEventType, ...args: any[]) {
@@ -155,6 +167,238 @@
      this.listenMapClick();
      this.addBasicControl();
      this.initEvent();
   }
   gaodeApiKey = 'eea6302da02576fe3f3dd3ba1fbe0a04';
   locationLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   centerLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   async locationCurrent() {
      const position = await getCurrentPosition();
      if (!position) return;
      const { latitude, longitude } = position;
      this.map.getView().setCenter(fromLonLat([longitude, latitude]));
      this.map.getView().setZoom(15);
      // 移除旧图层
      this.map.removeLayer(this.locationLayer);
      this.map.removeLayer(this.centerLayer);
      // 创建定位点图层
      this.locationLayer = new VectorLayer({
         source: new VectorSource({
            features: [
               new Feature({
                  geometry: new Point(fromLonLat([longitude, latitude])),
               }),
            ],
         }),
         style: new Style({
            // 外圆
            image: new Circle({
               radius: 20,
               fill: new Fill({
                  color: 'rgba(24, 144, 255, 0.1)',
               }),
               stroke: new Stroke({
                  color: 'rgba(24, 144, 255, 0.3)',
                  width: 2,
               }),
            }),
         }),
         minZoom: 12,
      });
      // 创建中心点图层
      this.centerLayer = new VectorLayer({
         source: new VectorSource({
            features: [
               new Feature({
                  geometry: new Point(fromLonLat([longitude, latitude])),
               }),
            ],
         }),
         style: new Style({
            // 内圆
            image: new Circle({
               radius: 6,
               fill: new Fill({
                  color: '#1890ff',
               }),
               stroke: new Stroke({
                  color: '#fff',
                  width: 2,
               }),
            }),
         }),
      });
      // 添加新图层
      this.map.addLayer(this.locationLayer);
      this.map.addLayer(this.centerLayer);
      return position;
   }
   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=${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
      const response = await axios.get(url);
      return response.data;
   }
   readWKT(wktStr) {
      const srid = wktStr.match(/SRID=(\d+);/)?.[1];
      const standardWktStr = wktStr.replace(/SRID=\d+;/, '');
      const feature = new WKT().readFeature(standardWktStr, {
         dataProjection: `EPSG:${srid}`,
      });
      return feature;
   }
   drawLayer: VectorLayer<VectorSource<Feature<Geometry>>, Feature<Geometry>> = null;
   private isDrawStatus = false;
   removeDrawLayer() {
      if (!this.drawLayer) return;
      this.map.removeLayer(this.drawLayer);
      this.drawLayer = null;
   }
   drawPolygon() {
      if (this.isDrawStatus) return;
      this.isDrawStatus = true;
      return new Promise((resolve) => {
         // 创建绘制交互
         const draw = new Draw({
            type: 'Polygon',
         });
         // 添加绘制交互到地图
         this.map.addInteraction(draw);
         // 监听绘制完成事件
         draw.on('drawend', (event) => {
            const feature = event.feature;
            const geometry = feature.getGeometry();
            const extent = geometry.getExtent();
            this.drawLayer = new VectorLayer({
               source: new VectorSource({
                  features: [feature],
               }),
               style: new Style({
                  stroke: new Stroke({
                     color: '#1677ff',
                     width: 2,
                  }),
                  fill: new Fill({
                     color: 'rgba(22, 119, 255, 0.1)',
                  }),
               }),
            });
            // 添加多边形图层到地图
            this.map.addLayer(this.drawLayer);
            // 移除绘制交互
            this.map.removeInteraction(draw);
            setTimeout(() => {
               this.isDrawStatus = false;
            }, 300);
            // 返回范围
            resolve(extent);
         });
      });
   }
   drawRectangle() {
      if (this.isDrawStatus) return;
      this.isDrawStatus = true;
      return new Promise((resolve) => {
         // 创建绘制交互
         const draw = new Draw({
            type: 'Circle',
            geometryFunction: createBox(),
         });
         // 添加绘制交互到地图
         this.map.addInteraction(draw);
         // 监听绘制完成事件
         draw.on('drawend', (event) => {
            const feature = event.feature;
            const geometry = feature.getGeometry();
            const extent = geometry.getExtent();
            this.drawLayer = new VectorLayer({
               source: new VectorSource({
                  features: [feature],
               }),
               style: new Style({
                  stroke: new Stroke({
                     color: '#1677ff',
                     width: 2,
                  }),
                  fill: new Fill({
                     color: 'rgba(22, 119, 255, 0.1)',
                  }),
               }),
            });
            // 添加新的feature
            // this.drawLayer.getSource().addFeature(feature);
            // 添加矩形图层到地图
            this.map.addLayer(this.drawLayer);
            // 移除绘制交互
            this.map.removeInteraction(draw);
            setTimeout(() => {
               this.isDrawStatus = false;
            }, 300);
            // 返回范围
            resolve(extent);
         });
      });
   }
   clearObjectSearch() {
      this.highlightSearch([]);
   }
   displaySearchResult(searchItem) {
      if (!searchItem?.WKT) return;
      const feature = this.readWKT(searchItem.WKT);
      this.highlightSearch(feature);
      const geometry = feature.getGeometry();
      this.map.getView().fit(geometry.getExtent(), {
         // padding: [100, 100, 100, 100],
         maxZoom: 15,
      });
      return feature;
   }
   zoomToFeatures(features) {
      if (features.length === 0) return;
      // 获取所有 feature 的最小外接矩形
      const extent = features.reduce((acc, feature) => {
         const featureExtent = feature.getGeometry().getExtent();
         if (!acc) return featureExtent;
         return extend(acc, featureExtent);
      }, null);
      // 调整视图以适应最小外接矩形
      this.map.getView().fit(extent, {
         maxZoom: 15,
         padding: [50, 50, 50, 50], // 添加内边距使视图更美观
      });
   }
   updateSize() {
      this.map.updateSize();
   }
   initEvent() {
@@ -458,6 +702,7 @@
      overlay.set('type', OverlayType.Marker);
      // 添加点击事件
      markerImg.addEventListener('click', (event) => {
         if (this.isDrawStatus) return;
         if (markerOpt.icon.selectUrl) {
            markerImg.src = markerOpt.icon.selectUrl;
         }
@@ -467,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();
@@ -487,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);
      }
@@ -505,6 +760,7 @@
    */
   listenMapClick() {
      this.map.on('click', (event) => {
         if (this.isDrawStatus) return;
         // const features = this.map.getFeaturesAtPixel(event.pixel);
         const features = [];
         const layers: Layer<Source, LayerRenderer<any>>[] = [];
@@ -514,11 +770,12 @@
         });
         const feature = features[0];
         const layer = layers[0];
         if (layer === this.drawLayer) return;
         if (feature !== this.activeFeature.value) {
            this.emit('featureChange', feature, layer);
         }
         if (feature) {
            console.log('🚀 ~ feature:', feature);
            const otype = feature.get('otype');
            console.log('🚀 ~ otype:', otype);
            const oname = feature.get('oname');
@@ -528,7 +785,7 @@
            const properties = feature.getProperties();
            console.log('🚀 ~ properties:', properties);
         }
         this.displayFeatureInfo(feature);
         this.highlightSelect(feature);
         this.activeFeature.value = feature;
      });
   }
@@ -548,6 +805,30 @@
      return allLayers;
   }
   zoomToLayers() {
      let extent = this.getAllMarkerOverlaysExtent();
      const layers = this.getAllLayerModels();
      if (layers.length > 0) {
         // 获取所有图层的范围
         extent = layers.reduce((extent, layer) => {
            const layerExtent = layer.getExtent();
            if (!extent) {
               return layerExtent;
            }
            // 合并范围
            return extend(extent, layerExtent);
         }, extent);
      }
      // 聚焦到合并后的范围
      this.map.getView().fit(extent, {
         padding: [50, 50, 50, 50],
         maxZoom: 15,
      });
   }
   getAllLayerModels() {
      return this.layerInfo.value.reduce((preVal, curVal) => {
         if (curVal.children && curVal.children.length > 0) {
@@ -556,6 +837,189 @@
            return preVal;
         }
      }, []);
   }
   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 记录所有图层 */
@@ -714,9 +1178,7 @@
      this.map.addLayer(vectorTileLayer);
      return vectorTileLayer;
   }
   // highlightFeature = null;
   displayFeatureInfo(feature) {
   highlightFeature(feature) {
      const highlightStyle = {
         // Point: new Style({
         //    // image: new Circle({
@@ -772,6 +1234,110 @@
            },
         });
      }
   }
   private searchHighlightStyle = {
      // Point: new Style({
      //    // image: new Circle({
      //    //    radius: 5,
      //    //    fill: new Fill({ color: `blue` }),
      //    // }),
      //    image: new Circle({
      //       radius: 13,
      //       stroke: new Stroke({
      //          color: `blue`,
      //          width: 3,
      //       }),
      //    }),
      // }),
      // Point:this.getPointHighLightStyle.call(this,feature),
      Point: new Style({
         // image: new Circle({
         //    radius: 5,
         //    fill: new Fill({ color: `blue` }),
         // }),
         image: new Circle({
            radius: 13,
            stroke: new Stroke({
               color: `yellow`,
               width: 3,
            }),
         }),
      }),
      LineString: new Style({
         stroke: new Stroke({
            color: `yellow`,
            width: 5,
         }),
      }),
      Polygon: new Style({
         stroke: new Stroke({
            color: `yellow`,
            width: 5,
         }),
         // fill: new Fill({
         //    color: `rgba(0, 0, 255, 0.1)`,
         // }),
      }),
   };
   private selectHighlightStyle = {
      // Point: new Style({
      //    // image: new Circle({
      //    //    radius: 5,
      //    //    fill: new Fill({ color: `blue` }),
      //    // }),
      //    image: new Circle({
      //       radius: 13,
      //       stroke: new Stroke({
      //          color: `blue`,
      //          width: 3,
      //       }),
      //    }),
      // }),
      // Point:this.getPointHighLightStyle.call(this,feature),
      Point: new Style({
         // image: new Circle({
         //    radius: 5,
         //    fill: new Fill({ color: `blue` }),
         // }),
         image: new Circle({
            radius: 13,
            stroke: new Stroke({
               color: `blue`,
               width: 3,
            }),
         }),
      }),
      LineString: new Style({
         stroke: new Stroke({
            color: `blue`,
            width: 5,
         }),
      }),
      Polygon: new Style({
         stroke: new Stroke({
            color: `blue`,
            width: 5,
         }),
         // fill: new Fill({
         //    color: `rgba(0, 0, 255, 0.1)`,
         // }),
      }),
   };
   highlightSelect(feature) {
      // 创建高亮图层
      if (!this.interactLayer) {
         this.interactLayer = new VectorLayer({
            source: new VectorSource(),
            map: this.map,
            style: (feature) => {
               const type = feature.getGeometry().getType();
               return this.selectHighlightStyle[type];
            },
         });
      }
      // 设置高亮要素
      if (feature !== this.activeFeature.value) {
@@ -786,6 +1352,32 @@
      }
   }
   private preSearchHighlightFeatures: Feature[] = [];
   highlightSearch(features) {
      if (!Array.isArray(features)) {
         features = [features];
      }
      // 创建高亮图层
      if (!this.searchHighlightLayer) {
         this.searchHighlightLayer = new VectorLayer({
            source: new VectorSource(),
            map: this.map,
            style: (feature) => {
               const type = feature.getGeometry().getType();
               return this.searchHighlightStyle[type];
            },
         });
      }
      if (this.preSearchHighlightFeatures && this.preSearchHighlightFeatures.length > 0) {
         this.searchHighlightLayer.getSource().removeFeatures(this.preSearchHighlightFeatures);
      }
      // 设置高亮要素
      if (features && features.length > 0) {
         this.searchHighlightLayer.getSource().addFeatures(features);
      }
      this.preSearchHighlightFeatures = features;
   }
   getWMTS = () => {
      const projection = getProjection('EPSG:3857');
      const projectionExtent = projection.getExtent();