高德地图:加载坐标,标记更新切换
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 = () => {
window._AMapSecurityConfig = { securityJsCode: '' };
AMapLoader.load({
key: '',
version: '2.0',
})
.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();
}, []);
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);
}
};
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,
});
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;