/** @format */ import _ from 'lodash'; import { useEffect } from 'react'; interface AmapBoxProps { parentId: string; data: any; } const Basic2DMapLabel = (props: AmapBoxProps) => { const { parentId = '1', data = [ { level: 'province', name: '浙江省', }, ], } = props; useEffect(() => { // console.log(' window.__map2d[parentId]?.map', window.__map2d[parentId]?.map); if (!window.__map2d[parentId]?.map) return; data && data.length > 0 && data.map((item: any) => { drawBounds(item); }); return () => { window.__map2d[parentId]?.map.remove(polygons); }; }, [window.__map2d[parentId]?.map, data]); let district = null; const polygons = []; function drawBounds(item: any) { //加载行政区划插件 if (!district) { //实例化DistrictSearch const opts = { subdistrict: 0, //获取边界不需要返回下级行政区 extensions: 'all', //返回行政区边界坐标组等具体信息 level: 'province', //查询行政级别为 市 }; district = new AMap.DistrictSearch(opts); } //行政区查询 district.setLevel(item.level); district.search(item.name, function(status: any, result: any) { // window.__map2d[parentId]?.map.remove(polygons); //清除上次结果 // polygons = []; const bounds = result.districtList[0].boundaries; if (bounds) { for (let i = 0, l = bounds.length; i < l; i++) { //生成行政区划polygon const polygon = new AMap.Polygon({ strokeWeight: 2, path: bounds[i], fillOpacity: 0, fillColor: 'rgba(128, 216, 255,0.1)', strokeColor: '#99ffff', }); polygons.push(polygon); } } window.__map2d[parentId]?.map.add(polygons); // window.__map2d[parentId]?.map.setFitView(polygons); //视口自适应 }); } return null; }; export default Basic2DMapLabel;