天地图添加多个覆盖物,点击切换选中icon

  

天地图添加多个覆盖物,点击覆盖物,切换选中的icon,移除之前的icon,再次点击移除之前的。。。

这个是react写的,先是确定中心位置,然后渲染点位,添加覆盖物,选中icon的不同, 

主要看函数:  marker.addEventListener('click', (event: any) => {});   这个函数是主要的

 

看先效果:

json数据:参考网站

http://datav.aliyun.com/portal/school/atlas/area_selector?spm=a2crr.23498931.0.0.685915dd8QQdlv

 

import React, { useState, useEffect, useRef } from 'react';
import { useUpdateEffect, useEffectOnce, useSize } from 'react-use';
//@ts-ignore
import T from 'TMap';
import { isEmpty } from 'lodash';
// 请求
import { RequestObj } from '@/services/publicPowerWarning';
// 图片
import map_green from '@/assets/publicPowerWarning/map_green.png';
import map_red from '@/assets/publicPowerWarning/map_red.png';
import map_yellow from '@/assets/publicPowerWarning/map_yellow.png';
import map_active from '@/assets/publicPowerWarning/map_active.png';
import map_red_and_yellow from '@/assets/publicPowerWarning/map_red_and_yellow.png';
// style
import stylesMap from './tdMapCustom.less';
import styles from '../index.less';

const MapBox = () => {
  const mapRef = useRef<any>();
  const [initDataMap, setInitDataMap] = useState({
    centerCity: '滨江区',
    defaultZoom: 13,
    centerPoint: { lng: 120.195335, lat: 30.181746 },
  });
  const [zoom, setZoom] = useState<any>(13);
  const [flag, setFlag] = useState(true);

  const getEarlyWarningProjectMap = (params: any) => {
    RequestObj.earlyWarningProjectMap(params).then((res: any) => {
      if (res.code === 200) {
        if (flag) {
          initMap(res.data);
          setFlag(false);
        } else {
          mapRef?.current.clearOverLays();
          setCircleMarker(res.data, mapRef?.current);
        }
      }
    });
  };

  // 设置显示地图的中心点和级别
  const setCenterCity = (city: string, map: any) => {
    const { defaultZoom } = initDataMap;
    if (city) {
      new T.LocalSearch(map, {
        pageCapacity: 10,
        onSearchComplete: (result: any) => {
          const { lonlat } = result.area || {};
          if (lonlat) {
            const ll = lonlat.split(',');
            map.setStyle('indigo');
            map.centerAndZoom(new T.LngLat(120.195335, 30.181746), defaultZoom);
          }
        },
      }).search(city);
    } else {
      new T.LocalCity().location(function(e: any) {
        map.centerAndZoom(e.lnglat, defaultZoom);
      });
    }
  };

  // 设置项目级的marker
  const setCircleMarker = (markers: any[], map: any) => {
    if (mapRef.current && markers instanceof Array) {
      const markerInfoWin = new T.InfoWindow('', {
        // maxHeight: 250,
        maxWidth: 500,
        autoPan: true,
        closeButton: false,
        closeOnClick: true,
        offset: new T.Point(0, -15),
      });

      let pointColorFlag = false;

      let markerActive = ''
      let markerOld = ''
      markers
        .filter(item => item.lng && item.lat)
        .map((item, index) => {
          let bgUrl: any = null;
          let borderColor: any = null;
          if (item?.alarmColor === 1) {
            bgUrl = map_green;
            borderColor = `
              background: rgba(0,0,0,0.80);
              border: 2px solid #44F35F;
              box-shadow: inset 0 1px 60px 0 rgba(12,161,255,0.50);
            `;
          }
          if (item?.alarmColor === 2) {
            bgUrl = map_yellow;
            borderColor = `
              background: rgba(0,0,0,0.80);
              border: 2px solid #F7D93F;
              box-shadow: inset 0 1px 60px 0 rgba(12,161,255,0.50);
            `;
          }
          if (item?.alarmColor === 3) {
            bgUrl = map_red;
            borderColor = `
              background: rgba(0,0,0,0.80);
              border: 2px solid #FF3B3B;
              box-shadow: inset 0 1px 60px 0 rgba(12,161,255,0.50);
            `;
          }
          if (item?.alarmColor === 4) {
            bgUrl = map_red_and_yellow;
            borderColor = `
              background: rgba(0,0,0,0.80);
              border: 2px solid;
              border-image: linear-gradient(to bottom, #FF3B3B, #F7D93F) 1;
              box-shadow: inset 0 1px 60px 0 rgba(12,161,255,0.50);
            `;
          }
          let bgHoverUrl = map_active;

          const lnglat = new T.LngLat(item.lng, item.lat);
          let marker = new T.Marker(lnglat, {
            icon: new T.Icon({ iconUrl: bgUrl, iconSize: new T.Point(24, 24) }),
          });
          map.addOverLay(marker);
          
          function callbacks () {
            markerInfoWin.setContent(`
              <div key=${index} style="position:relative;width:calc(100% + 18px);padding: 12px 8px;color:#fff;border-radius: 10px;${borderColor}">
                <div style="font-size:16px;font-weight:bold;color:#03FCFE">${item.projectName}</div>
                <div style="font-size:14px;font-weight:400;">施工许可证号:${item.builderLicenseNumber}</div>
                <div style="font-size:14px;font-weight:400;">建设单位:${item.buildNames || ''}</div>
                <div style="font-size:14px;font-weight:400;">总承包单位:${item.contractNames || ''}</div>
                <div style="font-size:14px;font-weight:400;">监理单位:${item.supervisorNames || ''}</div>
                <div style="font-size:14px;font-weight:400;">设计单位:${item.designNames || ''}</div>
                <div style="font-size:14px;font-weight:400;">勘查单位:${item.surveyNames || ''}</div>
                <div style="font-size:14px;font-weight:400;color:#FF3B3B;">红色预警:${item.redAlarmNum}</div>
                <div style="font-size:14px;font-weight:400;color:#F7D93F;">黄色预警:${item.yellowAlarmNum}</div>
              </div>`);
            marker.openInfoWindow(markerInfoWin);
          }

          marker.addEventListener('mouseover', (event:any) => {});
          marker.addEventListener('mouseout', () => {});

          marker.addEventListener('click', (event: any) => {
            callbacks()  
            marker.openInfoWindow(markerInfoWin);
            if (pointColorFlag) {
              map.removeOverLay(markerActive);
              pointColorFlag = false;
              map.addOverLay(markerOld);
            }
            markerOld = event.target;
            map.removeOverLay(markerOld);
            const lnglat1 = new T.LngLat(event.lnglat.lng, event.lnglat.lat);
            markerActive = new T.Marker(lnglat1, {
              icon: new T.Icon({ iconUrl: bgHoverUrl, iconSize: new T.Point(36, 30) }),
            });
            map.addOverLay(markerActive);
            pointColorFlag = true;
          });

          map.addEventListener('click', () => {
            marker.setIcon(new T.Icon({ iconUrl: bgUrl, iconSize: new T.Point(24, 24) }));
            map.addOverLay(markerOld);
            map.removeOverLay(markerActive);
          });
        });
    }
  };
    
  // 根据levelCode向地图中画一个区域轮廓
  const addAreaCoordinate = (map: any, isResetCenter?: boolean) => {

    const obj = gs_json || ''; // 这个是一个区域的json数据,可以下载json,参考网站  http://datav.aliyun.com/portal/school/atlas/area_selector?spm=a2crr.23498931.0.0.685915dd8QQdlv 

    if (isResetCenter) {
      const center = obj?.features[0]?.properties?.center;
      map.centerAndZoom(
        new T.LngLat(center[0], center[1]),
        map.getZoom()
      );
    }

    const points: any[] = [];
    obj?.features[0]?.geometry?.coordinates[0][0].map((item: any) => {
      points.push(new T.LngLat(item[0], item[1]));
    });
    // 创建面对象
    let polygon = new T.Polygon(points, {
      color: '#1CB9FF',
      weight: 3,
      opacity: 1,
      fillColor: '#1CB9FF',
      fillOpacity: 0.1,
    });

    polygon.addEventListener('mouseover', () => {
      polygon = new T.Polygon(points, {
        color: '#1CB9FF',
        weight: 3,
        opacity: 0.5,
        fillColor: '#1CB9FF',
        fillOpacity: 0.05,
      });
    });

    polygon.addEventListener('mouseout', () => {
      polygon = new T.Polygon(points, {
        color: '#1CB9FF',
        weight: 3,
        opacity: 0.5,
        fillColor: '#1CB9FF',
        fillOpacity: 0.05,
      });
    });
    // map.clearOverLays();
    // setCircleMarker(handleMarkerData('projectMarkers'));
    // 向地图上添加面
    map.addOverLay(polygon);

  };  
    
  //初始化地图
  const initMap = (paramsData: any) => {
    const { centerCity, defaultZoom, centerPoint } = initDataMap;
    const map = new T.Map('mapDiv', { minZoom: 12, maxZoom: 18 }); // maxBounds:new T.LngLatBounds([30,120],[31,120.7])
    map.centerAndZoom(new T.LngLat(centerPoint.lng, centerPoint.lat), defaultZoom);
    map.setStyle('indigo');
    mapRef.current = map;
    map.addEventListener('zoomend', ({ type, target }: any) => {
      setZoom(target.getZoom());
    });
    setCenterCity(centerCity, map);
    setCircleMarker(paramsData, map);
    addAreaCoordinate(map)
  };

  useEffect(() => {
    getEarlyWarningProjectMap({}); // 获取点位
  }, []);

  return (
    <div className={styles.tianDiMapBox}>
      <div className={styles.map_box_position}>
        <div id="mapDiv" style={{ width: '100%', height: 515 }} className={stylesMap.tdt} />
      </div>
    </div>
  );
};
export default MapBox;

 

posted @ 2022-08-26 16:04  有只橘猫  阅读(859)  评论(0编辑  收藏  举报