Newer
Older
KaiFengH5 / src / utils / mapbox.js
@zhangdeliang zhangdeliang on 24 May 13 KB 项目初始化
import 'mapbox-gl/dist/mapbox-gl.css';
import mapboxgl from 'mapbox-gl';
import * as turf from '@turf/turf';
import WKT from 'terraformer-wkt-parser';

let map = null;
mapboxgl.accessToken =
  'pk.eyJ1IjoibHVrYXNtYXJ0aW5lbGxpIiwiYSI6ImNpem85dmhwazAyajIyd284dGxhN2VxYnYifQ.HQCmyhEXZUTz3S98FMrVAQ';
/**创建初始化地图
 *@param 初始化地图属性
 */
export const initMap = (mapConfig) => {
  mapConfig.style = {
    version: 8,
    name: 'base',
    sprite: 'mapbox://sprites/mapbox/streets-v8',
    glyphs: 'mapbox://fonts/mapbox/{fontstack}/{range}.pbf',
    sources: {
      // "tian-satellite": {
      //   // 天地图 卫星影像
      //   type: "raster",
      //   tiles: ["http://t0.tianditu.gov.cn/img_w/wmts?tk=243c6497cbe6d26ba7a6420b3c3a3000&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles"],
      //   tileSize: 256,
      // },
      // "tian-satellitelabel": {
      //   // 天地图 卫星影像注记
      //   type: "raster",
      //   tiles: ["http://t0.tianditu.gov.cn/cia_w/wmts?tk=243c6497cbe6d26ba7a6420b3c3a3000&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles"],
      //   tileSize: 256,
      // },
      'tian-vector': {
        // 天地图 矢量地图
        type: 'raster',
        tiles: ['https://wprd01.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=2&style=7'],
        tileSize: 256,
      },
      'tian-vectorlabel': {
        // 天地图 矢量地图注记
        type: 'raster',
        tiles: [
          'http://t0.tianditu.gov.cn/cva_w/wmts?tk=243c6497cbe6d26ba7a6420b3c3a3000&SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&FORMAT=tiles',
        ],
        tileSize: 256,
      },
    },
    layers: [
      // {
      //   id: "tian-satellite",
      //   type: "raster",
      //   source: "tian-satellite",
      //   layout: {
      //     visibility: "visible",
      //   },
      //   minzoom: 0,
      //   maxzoom: 22,
      // },
      // {
      //   id: "tian-satellitelabel",
      //   type: "raster",
      //   source: "tian-satellitelabel",
      //   layout: {
      //     visibility: "visible",
      //   },
      //   minzoom: 0,
      //   maxzoom: 22,
      // },
      {
        id: 'tian-vector',
        type: 'raster',
        source: 'tian-vector',
        layout: {
          visibility: 'visible',
        },
      },
      {
        id: 'tian-vectorlabel',
        type: 'raster',
        source: 'tian-vectorlabel',
        layout: {
          visibility: 'visible',
        },
      },
    ],
  };
  map = new mapboxgl.Map(mapConfig);
  //添加比例尺
  var scale = new mapboxgl.ScaleControl({
    maxWidth: 100,
    unit: 'metric',
  });
  map.addControl(scale, 'bottom-left');
  return map;
};

/**巡查
 *
 * @param {*} positionArr 接收移动端坐标
 * @param {*} key         图层ID
 * @param {*} Linearry    经纬度数组
 */
export const RiverXunCha = (key, positionArr, Linearry) => {
  let sourceId = key;
  let layerId = key;
  let lnglat = [Number(positionArr[0].P), Number(positionArr[0].O)];
  Linearry.push(lnglat);
  var geojson = {
    type: 'FeatureCollection',
    features: [
      {
        type: 'Feature',
        geometry: {
          type: 'LineString',
          coordinates: Linearry,
        },
      },
    ],
  };
  !map.getSource(sourceId) && map.addSource(sourceId, { type: 'geojson', data: geojson });
  //添加动态线
  !map.getLayer(layerId) &&
    map.addLayer({
      id: layerId,
      type: 'line',
      source: sourceId,
      layout: {
        'line-cap': 'round',
        'line-join': 'round',
      },
      paint: {
        'line-color': 'red',
        'line-width': 5,
        'line-opacity': 0.8,
      },
    });
  // geojson.features[0].geometry.coordinates = Linearry;
  map.getSource(sourceId).setData(geojson);
};

/**WKT转geojson
 *
 */
export const getWKTtoGeojson = (arry) => {
  return {
    type: 'FeatureCollection',
    features: arry.map((item) => {
      if (item.geometrys != '' && item.geometrys != null) {
        let geometry = WKT.parse(item.geometrys);
        return { type: 'Feature', geometry, properties: item };
      }
    }),
  };
};

/**历史路径
 *
 */
export const XunChaRecord = (data, key) => {
  let sourceId = key;
  let layerId = key;
  let arry = []; //实时坐标
  if (data.features[0] != undefined) {
    let stept = turf.lineChunk(data, 0.05, { units: 'miles' }); //分割线段
    for (let i = 0; i < stept.features.length; i++) {
      for (let j = 0; j < stept.features[i].geometry.coordinates.length; j++) {
        arry.push(stept.features[i].geometry.coordinates[j]);
      }
    }

    let end = arry.length - 1;

    map.flyTo({
      center: turf.center(data).geometry.coordinates,
      zoom: 12.5,
      speed: 0.8,
    });
    window.marker1 == null;
    window.marker1 = new mapboxgl.Marker({
      color: 'red',
      scale: 0.8,
      draggable: false,
      pitchAlignment: 'auto',
      rotationAlignment: 'auto',
    })
      .setLngLat(arry[0])
      .addTo(map);
    window.marker2 == null;
    window.marker2 = new mapboxgl.Marker({
      color: 'green',
      scale: 0.8,
      draggable: false,
      pitchAlignment: 'auto',
      rotationAlignment: 'auto',
    })
      .setLngLat(arry[end])
      .addTo(map);
    !map.getSource(sourceId) && map.addSource(sourceId, { type: 'geojson', data: data });
    !map.getLayer(layerId) &&
      map.addLayer({
        id: layerId,
        type: 'line',
        source: sourceId,
        layout: {
          'line-cap': 'round',
          'line-join': 'round',
        },
        paint: {
          'line-color': 'rgba(224, 15, 206, 1)',
          'line-width': 5,
          'line-opacity': 0.8,
        },
      });
  }
};

/**添加geojson线
 *
 */
export const addJsonLineLayer = (key, data, color, visible = true) => {
  let sourceId = key;
  let layerId = key;
  !map.getSource(sourceId) &&
    map.addSource(sourceId, {
      type: 'geojson',
      data: data,
    });
  !map.getLayer(layerId) &&
    map.addLayer({
      id: layerId,
      type: 'line',
      source: sourceId,
      layout: {
        visibility: visible ? 'visible' : 'none', // 可见性(可选,可选值为 none、visible,默认值为 visible)
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-width': 6,
        'line-color': color,
      },
    });
};
/***设置图层可见性
 * @param key       图层名
 * @param visible   可选值为 "none"、"visible",
 */
export const setVisible = (key, visible) => {
  let layerId = key;
  if (map.getLayer(layerId)) {
    map.setLayoutProperty(layerId, 'visibility', visible);
  }
};

/**添加弹窗
 *@param key
 */
export const markerPopup = (key, type) => {
  window.YSpopup = null;
  window.WSpopup = null;
  map.on('click', key, function (e) {
    !!YSpopup && YSpopup.remove();
    !!WSpopup && WSpopup.remove();
    let content = e.features[0].properties;
    let center = turf.center(e.features[0].geometry);
    let lonlat = center.geometry.coordinates;
    if (type == 'YS') {
      YSpopup = new mapboxgl.Popup()
        .setLngLat(lonlat)
        .setHTML(
          '<div class="markerBody" ><div class="markerItem"><div class="itemName">管段编号:</div>' +
            '<div class="itemContent">' +
            content.pipecode +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">管段类型名称:</div>' +
            '<div class="itemContent">' +
            content.pipetype +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷类型:</div>' +
            '<div class="itemContent">' +
            content.faultclass +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷类型名称:</div>' +
            '<div class="itemContent">' +
            content.faultname +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷状态:</div>' +
            '<div class="itemContent">' +
            content.faultsta +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷等级:</div>' +
            '<div class="itemContent">' +
            content.faultrank +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">建议整治方法:</div>' +
            '<div class="itemContent">' +
            content.repairmeth +
            '</div></div></div>'
        )
        .addTo(map);
    }
    if (type == 'WS') {
      WSpopup = new mapboxgl.Popup()
        .setLngLat(lonlat)
        .setHTML(
          '<div class="markerBody" ><div class="markerItem"><div class="itemName">管段编号:</div>' +
            '<div class="itemContent">' +
            content.pipecode +
            '</div></div>' +
            '<div class="markerItem><div class="itemName">管段类型名称:</div>' +
            '<div class="itemContent">' +
            content.pipetype +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷类型:</div>' +
            '<div class="itemContent">' +
            content.faultclass +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷类型名称:</div>' +
            '<div class="itemContent">' +
            content.faultname +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷状态:</div>' +
            '<div class="itemContent">' +
            content.faultsta +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">缺陷等级:</div>' +
            '<div class="itemContent">' +
            content.faultrank +
            '</div></div>' +
            '<div class="markerItem"><div class="itemName">建议整治方法:</div>' +
            '<div class="itemContent">' +
            content.repairmeth +
            '</div></div></div>'
        )
        .addTo(map);
    }
  });
  map.on('mouseenter', key, () => {
    map.getCanvas().style.cursor = 'pointer';
  });

  map.on('mouseleave', key, () => {
    map.getCanvas().style.cursor = '';
  });
};

/*************高亮显示线*************
 *
 */
export const addlineHiLight = (key, data, visible = true) => {
  let sourceId = key;
  let layerId2 = key + '_layer2';
  let layerId3 = key + '_layer3';
  !map.getSource(sourceId) && map.addSource(sourceId, { type: 'geojson', data: data });
  !map.getLayer(layerId2) &&
    map.addLayer({
      id: layerId2,
      type: 'line',
      source: sourceId,
      layout: {
        visibility: visible ? 'visible' : 'none', // 可见性(可选,可选值为 none、visible,默认值为 visible)
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-width': 6,
        'line-opacity': 1,
      },
    });
  !map.getLayer(layerId3) &&
    map.addLayer({
      id: layerId3,
      type: 'line',
      source: sourceId,
      layout: {
        visibility: visible ? 'visible' : 'none', // 可见性(可选,可选值为 none、visible,默认值为 visible)
        'line-join': 'round',
        'line-cap': 'round',
      },
      paint: {
        'line-width': 3,
        'line-color': 'rgb(255,255,0)',
        'line-opacity': 1,
      },
      filter: ['in', 'FID', ''],
    });
};
/*****点击高亮****
 *
 */
export const clickdisplay = (layerId2, layerId3) => {
  map.on('click', function (e) {
    if (!!map.getLayer(layerId2)) {
      var features = map.queryRenderedFeatures(e.point, {
        layers: [layerId2],
      });
      var filter = features.reduce(
        function (memo, feature) {
          memo.push(feature.properties.FID);
          return memo;
        },
        ['in', 'FID']
      );
      map.setFilter(layerId3, filter);
    }
  });
};
/**拓宽光效
 *  layername:lineCount_0
 *  timername:timertuokuan
 */
export const addAnimateXCline = (key, data) => {
  let sourceId = key;
  let colorList = [
    'rgba(0, 255, 0,1)',
    'rgba(14, 234, 14,0.9)',
    'rgba(34,217, 34,0.8)',
    'rgba(48, 138, 48,0.7)',
    'rgba(62, 160, 62,0.6)',
    'rgba(68, 143, 68,0.5)',
    'rgba(69, 255, 69,0.4)',
    'rgba(70, 109, 70,0.3)',
    'rgba(68, 96, 68,0.2)',
    'rgba(65, 84, 65,0.1)',
  ];
  let widthlist = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
  let blurlist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let colorNum = 0;

  !map.getSource(sourceId) && map.addSource(sourceId, { type: 'geojson', data: data });
  for (let i = 0; i < 10; i++) {
    addline(key + i, colorList[i], widthlist[i], blurlist[i]);
  }

  function addline(name, color, width, blur) {
    !map.getLayer(name) &&
      map.addLayer({
        id: name,
        source: sourceId,
        type: 'line',
        layout: {
          visibility: 'visible',
          'line-join': 'round',
          'line-cap': 'round',
        },
        paint: {
          'line-color': color,
          'line-width': width,
          'line-blur': blur,
        },
      });
  }
  window.timertuokuan = null;
  clearInterval(window.timertuokuan);
  window.timertuokuan = setInterval(() => {
    colorNum++;
    for (let i = 0; i < 10; i++) {
      var countNumShow = colorNum % 10;
      var pageNum = i % 10;
      var lineName = key + i;
      var totalNum = pageNum - countNumShow;
      if (totalNum <= 0) {
        map.setPaintProperty(lineName, 'line-color', colorList[9 - Math.abs(totalNum)]);
        map.setPaintProperty(lineName, 'line-width', widthlist[9 - Math.abs(totalNum)]);
        map.setPaintProperty(lineName, 'line-blur', blurlist[9 - Math.abs(totalNum)]);
      }
      if (totalNum > 0) {
        map.setPaintProperty(lineName, 'line-color', colorList[totalNum - 1]);
        map.setPaintProperty(lineName, 'line-width', widthlist[totalNum - 1]);
        map.setPaintProperty(lineName, 'line-blur', blurlist[totalNum - 1]);
      }
    }
    map.triggerRepaint();
  }, 500);
};