/** @format */ import _ from 'lodash'; import { useEffect } from 'react'; import { createInfoWindow } from '../../../utils/index'; type FontType = { color: string; fontFamily: string; fontWeight: number; fontSize: number; shadow: string; }; interface AmapBoxProps { parentId: string; style: { label: string; textStyle: FontType; }; data: { lat: number; lng: number; info?: string; content?: string; title?: string; [key: string]: any; }; windows?: { [key: string]: any }; } const Basic2DMapLabel = (props: AmapBoxProps) => { const { parentId = '1', style = { label: 'name', textStyle: { fontSize: 12, color: 'black', fontWeight: 500, fontFamily: '微软雅黑', shadow: 'black', }, }, data = [ { lat: 31.8998, lng: 102.2212, name: '点0', info: '234', content: '方恒假日酒店', title: '方恒假日酒店价格:318', }, { lat: 28.6542, lng: 120.079, name: '点1', info: '234', content: '方恒假日酒店', title: '方恒假日酒店价格:318', }, { lat: 24.0554, lng: 114.207, name: '点2', info: '234', content: '方恒假日酒店', title: '方恒假日酒店价格:318', }, ], windows = { isSelfSet: false, textStyle: { fontSize: 12, color: 'yellow', fontWeight: 500, fontFamily: '微软雅黑', shadow: 'black', }, lineHeight: 15, borderRadius: 5, padding: { paddingTop: 5, paddingBottom: 5, paddingLeft: 5, paddingRight: 5, }, background: 'red', close: { color: 'white', size: 10, marginTop: 5, marginRight: 5, }, }, } = props; const { label, textStyle } = style; let markerArr: any; useEffect(() => { if (!window.__map2d[parentId]?.map) return; const marks = buildMarker(data); window.__map2d[parentId]?.map.add(marks); // // 调试用 // window.__map2d[parentId]?.map.setFitView(); markerArr = marks; }, [window.__map2d[parentId]?.map, data]); useEffect(() => { if (!window.__map2d[parentId]?.map || windows.isSelfSet || !windows) return; markerArr && markerArr.forEach((item: any) => { item.on('click', textClick); }); }, [windows, data]); function closeInfoWindow() { window.__map2d[parentId]?.map.clearInfoWindow(); } function textClick(e: any) { const infoWindow = new AMap.InfoWindow({ isCustom: true, //使用自定义窗体 content: createInfoWindow( e.target.title, e.target.content, closeInfoWindow, windows, ), offset: new AMap.Pixel(16, -45), }); infoWindow.open(window.__map2d[parentId]?.map, e.target.getPosition()); } // 构造点标记 function buildMarker(markers: any) { const markersRes: any = []; markers && markers.length && markers.forEach(marker => { const text = new AMap.Text({ text: marker[label], anchor: 'center', // 设置文本标记锚点 // draggable: true, cursor: 'pointer', style: { 'font-size': textStyle.fontSize, color: textStyle.color, 'font-weight': textStyle.fontWeight, 'font-family': textStyle.fontFamily, shadow: textStyle.shadow, }, // angle: 10, position: [marker.lng, marker.lat], }); text.info = marker.info; text.content = marker.content; text.title = marker.title; markersRes.push(text); }); return markersRes; } return null; }; export default Basic2DMapLabel;