其中多点标注使用map去渲染生成(在地图上的点,生成的形状,生成的文本)
// 遍历标注数组,获取所有标注点的坐标
const points = markers.map(marker => new window.BMapGL.Point(marker.position[0], marker.position[1]));
添加辅助函数去渲染传进来的背景颜色
// 根据标注信息返回文本标注的样式对象
const getLabelStyle = (marker: Marker) => {
const backgroundColor = marker.labelBackgroundColor || "#353535";
return {
color: "#fff", // 字体颜色
backgroundColor, // 背景颜色
border: "none", // 边框样式
borderRadius: "5px", // 边框圆角
padding: "5px" // 内边距
};
};
完整代码
import React, { useEffect, useRef } from "react";
import avatar from "@/assets/images/avatar.png";
interface Marker {
position: [number, number];
labelContent?: string;
labelBackgroundColor?: string;
}
interface MapMarkerProps {
markers: Marker[];
apiKey?: string;
}
const MapMarker: React.FC<MapMarkerProps> = ({ markers }) => {
const mapContainerRef = useRef<HTMLDivElement>(null);
let map: any;
useEffect(() => {
initMap();
}, []);
const initMap = () => {
if (mapContainerRef.current) {
// 创建地图实例
map = new window.BMapGL.Map(mapContainerRef.current);
// 遍历标注数组,获取所有标注点的坐标
const points = markers.map(marker => new window.BMapGL.Point(marker.position[0], marker.position[1]));
// 根据标注点的坐标计算视野范围,并设置地图的中心点和缩放级别
const viewport = map.getViewport(points);
map.centerAndZoom(viewport.center, viewport.zoom);
// 遍历标注数组,创建并添加每个标注
markers.forEach(marker => {
// 定义标注的图标为圆形
const icon = new BMapGL.Icon(avatar, new BMapGL.Size(32, 32), {
anchor: new BMapGL.Size(16, 16), // 图标的中心点在图标图片中的位置
imageSize: new BMapGL.Size(32, 32), // 图标图片的大小
imageOffset: new BMapGL.Size(0, 0) // 图标所用图片相对于可视区域的偏移值
});
// 添加标注
const markerObj = new window.BMapGL.Marker(new window.BMapGL.Point(marker.position[0], marker.position[1]), { icon });
map.addOverlay(markerObj);
// 添加文本标注
if (marker.labelContent) {
const label = new BMapGL.Label(marker.labelContent, {
position: new BMapGL.Point(marker.position[0], marker.position[1]), // 文本标注所在的位置
offset: new BMapGL.Size(-10, 20) // 文本标注的偏移值
});
label.setStyle(getLabelStyle(marker));
markerObj.setLabel(label);
}
});
// 启用滚轮缩放
map.enableScrollWheelZoom(true);
}
};
// 根据标注信息返回文本标注的样式对象
const getLabelStyle = (marker: Marker) => {
const backgroundColor = marker.labelBackgroundColor || "#353535";
return {
color: "#fff", // 字体颜色
backgroundColor, // 背景颜色
border: "none", // 边框样式
borderRadius: "5px", // 边框圆角
padding: "5px" // 内边距
};
};
return (
<div className="card content-box">
<span style={{ marginBottom: "15px" }}>地图标注</span>
<div ref={mapContainerRef} style={{ height: "100%" }}></div>
</div>
);
};
export default MapMarker;
使用
interface Marker {
position: [number, number];
labelContent?: string;
labelBackgroundColor?: string;
}
const markers = [ { position: [116.404, 39.915], labelContent: "标注 1", labelBackgroundColor: "green" },
{ position: [116.405, 39.914], labelContent: "标注 1-1", labelBackgroundColor: "green" },
{ position: [116.418, 39.921], labelContent: "标注 2" },
{ position: [116.438, 39.931], labelContent: "标注 3" }
];
<MapMarker markers={markers as Marker[]} />