Newer
Older
KaiFengPC / src / views / gisMapPage / gisMapFunction.js
@zhangdeliang zhangdeliang on 23 May 11 KB 初始化项目
const mapConfig = {
  container: 'map',
  adcode: 411600,
  zoom: 13.6,
  pitch: 55,
  bearing: 0,
  fog: false,
  antialias: true, // 是否开启抗锯齿
  cursor: 'default',
  center: [113.953, 30.906],
  minZoom: 3,
  maxZoom: 22,
  isHotspot: false,
  isHotspotActive: false,
};
export default class NewFiberMapOperate {
  //地图实例
  map = null;
  //三维场景对象
  virtualSpaceObj = null;
  RunLineLayer = null;
  RayLayerObj = null;
  imageLayers = [];
  features = [];
  callbacks = {
    featureClick: undefined,
  };

  constructor(container, options) {
    this.initMap(container, options);
  }

  initMap(container, options) {
    let self = this;
    let config = Object.assign(mapConfig, options);
    config.container = container || config.container;
    config.style = {
      version: 8,
      sources: {
        'raster-tiles': {
          type: 'raster',
          tiles: ['http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}'],
          tileSize: 256,
        },
      },
      layers: [{ id: 'simple-tiles', type: 'raster', source: 'raster-tiles', minzoom: 0, maxzoom: 22 }],
    };
    self.map = new LKMap.Map(container, config);
    //self.map.setStyle(import.meta.env.VITE_APP_MAP_SRC + 'static/libs/map/nightblue.json');
  }

  //光效
  pointlight(geojson, key, lightColor) {
    let self = this;
    return geojson.features.forEach((feature, index) => {
      let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
      let coordinates = feature_84.geometry.coordinates;
      let rayList = [
        {
          id: 'Diffusion' + index,
          type: 'Diffusion',
          radius: 250,
          color: lightColor ? lightColor : '#ff0',
          position: [coordinates[0], coordinates[1], 0],
          speed: 10,
          DiffusionOptions: {
            count: 1,
            width: 5,
          },
          rotation: {
            x: 90,
            y: 0,
            z: 0,
          },
          newfiberId: key,
        },
      ];
      self.RayLayerObj.addModel(rayList, e => {});
      gcoord.transform(feature, gcoord.GCJ02, gcoord.WGS84);
    });
  }
  //添加点
  /**
   *
   * @param {*} geojson
   * @param {*} icon
   * @param {*} visible  true/false
   * @returns
   */
  addMarker(geojson, icon, id, visible, iconSize) {
    let self = this;
    console.log('geojson', geojson);
    return geojson.features.map(feature => {
      let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
      let lonlat = feature_84.geometry.coordinates;
      let marker = new LKMap.Marker({
        map: self.map,
        position: new LKMap.LngLat(...lonlat),
        anchor: 'bottom',
        extData: feature.properties,
        visible: visible,
        icon: new LKMap.Icon({
          size: iconSize ? new LKMap.Size(iconSize[0], iconSize[1]) : new LKMap.Size(45, 79),
          image: icon,
          scope: [0, 25],
          anchor: 'top-center',
        }),
        label: {
          scope: [15, 25],
          content:
            feature.properties.name ||
            feature.properties.Name ||
            feature.properties.stName ||
            feature.properties.pointNumber ||
            feature.properties.sewageName ||
            feature.properties.sectionName ||
            feature.properties.pumpName,
          direction: 'top',
          offset: new LKMap.Pixel(0, -5),
          style: {
            'background-color': 'rgba(255,255,255,1)',
            padding: '5px 10px',
            'border-radius': '4px',
            color: 'black',
            'box-shadow': '0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)',
          },
        },
      });
      marker.newfiberId = id;
      self.features.push(marker);
      if (self.callbacks.featureClick)
        self.features.flat(Infinity).forEach(i => {
          self.featureClick(i, self.callbacks.featureClick);
        });
      gcoord.transform(feature, gcoord.GCJ02, gcoord.WGS84);
      return marker;
    });
  }
  noClickMarker(geojson, icon, id) {
    let self = this;
    return geojson.features.map(feature => {
      let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
      let lonlat = feature_84.geometry.coordinates;
      let marker = new LKMap.Marker({
        map: self.map,
        position: new LKMap.LngLat(...lonlat),
        anchor: 'bottom',
        extData: feature.properties,
        icon: new LKMap.Icon({
          size: new LKMap.Size(34, 65),
          image: icon,
          scope: [5, -25],
          anchor: 'top-center',
        }),
      });
      marker.newfiberId = id;
      self.features.push(marker);
      return marker;
    });
  }
  //添加线
  addGeojsonLine(geojson, id, color) {
    let self = this;
    return geojson.features.map(feature => {
      let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
      let lonlat = feature_84.geometry.coordinates;
      let polyline = new LKMap.Polyline({
        map: self.map,
        path: new LKMap.LngLat(...lonlat),
        strokeWeight: 6,
        extData: feature.properties,
        strokeColor: color ? color : '#47E44E',
      });
      polyline.newfiberId = id;
      self.features.push(polyline);
      return polyline;
    });
  }
  //添加面
  addGeojsonPolygon(geojson, id, visible, color) {
    let self = this;
    return geojson.features.map(feature => {
      let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
      let lonlat = feature_84.geometry.coordinates[0];
      let polygon = new LKMap.Polygon({
        map: self.map,
        path: lonlat,
        strokeWeight: 1,
        strokeColor: '#f8f2f3',
        strokeOpacity: 1,
        fillColor: !!color ? color : !!feature.properties.fillColor ? feature.properties.fillColor : self.randomRgb(),
        fillOpacity: 0.8,
        extData: feature.properties,
        visible: visible,
      });
      polygon.newfiberId = id;
      self.features.push(polygon);
      //gcoord.transform(feature, gcoord.GCJ02, gcoord.WGS84);
      return polygon;
    });
  }
  //动态水体
  addDynamicWater(geojson, id) {
    let self = this;
    // 通过plugin方法加载VirtualSpace三维场景插件
    self.map.plugin(['VirtualSpace'], function () {
      // 实例化三维场景类
      let VirtualSpaceObject = new LKMap.VirtualSpace({
        map: self.map, // 必传
        defaultLights: true,
        sky: true,
        // fogColor:'#e6c9a3',
        // sky3: true,
        skyType: 'daylight', // 'daylight': 白天  'night':晚上  'morning':清晨   'sunset':日落
        // skyLightColor: '#ffffff',
        // skyLightIntensity: 1,
        GltfDoubleSide: false, // 高精地图是否开启双面绘制

        // isDrawBuildings: true
      });
      // 通过VirtualSpaceObject初始化类
      let waterLayerObj = new VirtualSpaceObject.WaterLayer({
        VirtualSpace: VirtualSpaceObject, // 将场景对象传给水面,必传
      });
      geojson.features.forEach((feature, index) => {
        let feature_84 = gcoord.transform(feature, gcoord.WGS84, gcoord.GCJ02);
        let geojson = feature_84.geometry.coordinates;
        waterLayerObj.addModel({
          id: id + index,
          scale: 1,
          distortionScale: 3,
          data: geojson,
          waterColor: '#5470c6',
          size: 1,
        });
      });
    });
  }
  //添加白膜
  addBuilding(geojson, id) {
    let self = this;
    self.map.addLayer({
      id: id,
      type: 'fill-extrusion',
      source: {
        type: 'geojson',
        data: geojson,
      },
      // //绘画功能
      paint: {
        // Get the fill-extrusion-color from the source 'color' property.   从source 'color'属性获取fill- extrusive -color。
        // 'fill-extrusion-color':'rgba(200, 100, 240, 0.4)',
        // "fill-extrusion-color":['get','color'],//加载数据中的颜色
        'fill-extrusion-color': {
          //根据数值中加载相对应颜色
          property: 'extend_3', // this will be your density property form you geojson
          stops: [
            [10, '#155ed7'],
            [20, '#2d6edb'],
            [30, '#447edf'],
            [80, '#5386da'],
            [100, '#7ba0dc'],
            [125, '#a1bfef'],
            [300, '#a1bfef'],
          ],
        },
        //    从source 'height'属性获取填充-挤出-高度。
        'fill-extrusion-height': ['get', 'extend_3'],
        'fill-extrusion-opacity': 1,
      },
    });
  }
  //添加wms
  addWMSLaters(key) {
    let self = this;
    let bboxs = [113.88115996100544, 30.80362587198562, 114.1592539075588, 31.005052001897184];
    let url = '/geoserver/xiaoganMapServer/wms?';
    let wasParam = {
      SERVICE: 'WMS',
      VERSION: '1.1.0',
      REQUEST: 'GetMap',
      FORMAT: 'image/png',
      TRANSPARENT: true,
      LAYERS: `xiaoganMapServer:${key}`,
      SRS: 'EPSG:3857',
      WIDTH: 256,
      HEIGHT: 256,
    };
    url =
      url +
      Object.keys(wasParam)
        .map(key => `${key}=${wasParam[key]}`)
        .join('&');
    let wmsLayer = new LKMap.TileLayer.WMS({
      getTileUrl: bbox => {
        let b = turf.bboxPolygon(bboxs);
        let a = turf.bboxPolygon(bbox.split(',').map(Number));
        a = gcoord.transform(a, gcoord.WebMercator, gcoord.WGS84);
        let i = turf.intersect(b, a);
        if (!!!i) return '';
        return url + `&bbox=${turf.bbox(gcoord.transform(a, gcoord.GCJ02, gcoord.WebMercator)).join(',')}`;
      },
    });
    wmsLayer.setMap(self.map);
    wmsLayer.newfiberId = key;
    self.features.push(wmsLayer);
  }
  //添加动态线
  addRunLine(geojson, key) {
    let self = this;
    let feature_84 = gcoord.transform(geojson.features[0], gcoord.WGS84, gcoord.GCJ02);
    let coordinates = feature_84.geometry.coordinates;
    let runLineList = [
      {
        image: 'https://lkimgyt.luokuang.com/1655260316814.png',
        height: 0,
        from: coordinates[0],
        to: coordinates[1],
        speed: 2,
        width: 20,
        newfiberId: key,
      },
    ];
    self.RunLineLayer.addLine(runLineList, e => {});
    // });
  }
  //添加弹窗
  createPopup(documentId, position) {
    let self = this;
    let position_gcj = gcoord.transform(turf.point(position), gcoord.WGS84, gcoord.GCJ02).geometry.coordinates;
    let element = document.getElementById(documentId);
    // 添加信息窗体
    let inforWindow = new LKMap.InforWindow({
      anchor: 'bottom',
      className: 'customClassName',
      content: element,
      isCustom: true, //使用自定义窗体
      showShadow: true, // 控制是否显示信息窗体阴影
      showShadowOffset: new LKMap.Pixel(0, -11), // 设置阴影偏移量
    });
    inforWindow.open(self.map, position_gcj);
    return inforWindow;
  }
  //feature点击事件
  featureClick(feature, callback) {
    if (feature.type !== 'tileLayer') feature.on('click', e => callback(e));
  }
  //获取图层
  getLayer(id) {
    let feature = [];
    this.features.forEach(item => {
      if (item.newfiberId && item.newfiberId == id) {
        feature.push(item);
      } else if (item.id && item.id == id) {
        feature.push(item);
      }
    });
    return feature;
  }
  //显隐控制
  setVisible(id, visible) {
    let feature = this.getLayer(id);
    feature.forEach(item => {
      visible == true ? item.show() : item.hide();
    });
  }
  //移除图层
  removeLayer(id) {
    let feature = this.getLayer(id);
    this.features.forEach((feature, index) => {
      if (feature.newfiberId && feature.newfiberId == id) {
        delete this.features[index];
      }
    });
    feature.forEach(item => {
      item.remove();
    });
    this.features = this.features.filter(Boolean);
  }
  //rgb颜色随机
  randomRgb() {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgba(${r},${g},${b},0.5)`;
  }
}