首页 前端知识 高德地图:加载坐标,标记更新切换

高德地图:加载坐标,标记更新切换

2024-06-22 01:06:48 前端知识 前端哥 276 364 我要收藏

高德地图:加载坐标,标记更新切换

//地图 坐标 标记 加载
const HomeMap = (props: HomeMapProps) => {
  const { path } = props;
  const { renderMapModal, showModal, isModalOpen } = useMapModal();
  const [iconPath, setIconPath] = useState('');
  const [iMap, setIMap] = useState<{
    icon: {
      Size: (arg0: number, arg1: number) => unknown;
      Pixel: (arg0: number, arg1: number) => unknown;
      Icon: new (arg0: { image: string }) => any;
      Marker: new (arg0: { icon: any; position: any; title: any }) => any;
    };
    remove: any;
  }>();
  const [AMap, setAMap] = useState<any>();
  const [markers, setMarkers] = useState<any>([]);
  const [lnglats, setLnglats] = useState<any>([]);
  const MarkersRef = useRef(null);

  const loadMap = () => {
    // 本地配置 安全密钥
    // @ts-ignore
    window._AMapSecurityConfig = { securityJsCode: '' };
    AMapLoader.load({
      key: '', // 申请好的Web端开发者Key,首次调用 load 时必填
      version: '2.0', // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
      // plugins: ['AMap.ElasticMarker', 'AMap.MassMarks',], // 需要使用的的插件列表,如比例尺'AMap.Scale'等
    })
      // eslint-disable-next-line @typescript-eslint/no-shadow
      .then(async (AMap) => {
        const initMap = new AMap.Map('container', {
          mapStyle: 'amap://styles/548230ec6ad312fccadc5fc55f76b336',
          viewMode: '3D',
          defaultCursor: 'pointer',
          zooms: [15, 20],
          center: [116.30069, 39.828497], //初始化地图中心点位置
          pitch: 95,
          zoom: 18, //初始化地图级别
        });

        setIMap(initMap);
        setAMap(AMap);
      })
      .catch((e) => {
        console.log(e);
      });
  };
  //加载地图 加载坐标
  useEffect(() => {
    loadMap();
  }, []);

  //生成坐标icon
  const renderIcon = (ipath: string) => {
    if (AMap && ipath) {
      return new AMap.Icon({
        image: `/marker/${ipath}.svg`,
        size: new AMap.Size(48, 48),
        imageSize: new AMap.Size(48, 48),
      });
    }
  };
  //更新标记
  const resetMap = (e?: { target: { getPosition: () => any; setIcon: (arg0: any) => void } }) => {
    const preIcon = renderIcon(iconPath);
    const clickIcon = e && renderIcon(iconPath + '_active');
    markers.map((item: { setIcon: (arg0: any) => void }) => {
      item.setIcon(preIcon);
    });
    e?.target.setIcon(clickIcon);
  };
  //关闭弹窗更新标记
  useEffect(() => {
    if (!isModalOpen && AMap && iconPath) {
      const preIcon = renderIcon(iconPath);
      markers.map((item: { setIcon: (arg0: any) => void }) => {
        item.setIcon(preIcon);
      });
    }
  }, [isModalOpen, AMap, iconPath]);
 // 记录标记
  useEffect(() => {
    MarkersRef.current = markers;
  }, [markers]);

  //清除标记
  const removeMarkers = () => {
    iMap?.remove(MarkersRef.current);
  };
  const fetchLnglats = async () => {
    const { header, body } = await getMapFrontList({ body: {} });
    if (header.code === '200') {
      const LnglatsArr = body.map((item: { lng: any; lat: any }) => {
        return [item.lng, item.lat];
      });
      setLnglats(LnglatsArr);
    }
  };

  //设置路由对应坐标icon
  useEffect(() => {
    if (path) {
      fetchLnglats();
      setIconPath();
    } else {
      removeMarkers();
    }
  }, [path]);

  // 加载地图标记绑定点击事件
  useEffect(() => {
    if (iconPath && lnglats && AMap) {
      removeMarkers();
      const preIcon = renderIcon();
      const markersList: ((prevState: any[]) => any[]) | any[] = [];
      lnglats.map((item: any) => {
        const marker = new AMap.Marker({
          map: iMap,
          position: item,
          icon: preIcon,
        });
        // map.setFitView()
        markersList.push(marker);
        marker.on(
          'click',
          (e: { target: { getPosition: () => any; setIcon: (arg0: any) => void } } | undefined) => {
            resetMap(e);
            showModal();
          },
        );
      });
      setMarkers(markersList);
    }
  }, [iconPath, lnglats, AMap]);

  return (
    <div className={styles.home_map} id="container">
      {renderMapModal()}
    </div>
  );
};

export default HomeMap;
转载请注明出处或者链接地址:https://www.qianduange.cn//article/13223.html
标签
评论
发布的文章

Java操作读取JSON文件

2024-07-21 00:07:04

Vue3.0环境搭建之npm的安装

2024-07-21 00:07:09

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!