先看效果:
步骤如下:
1、HTML
<div id="mapContainer" style={{width:"100%", height:"400px"}}/>
2、获取地图容器元素
const mapContainer = document.getElementById("mapContainer");
3、创建地图实例
const map = new BMapGL.Map("mapContainer");
4、设置中心点和缩放级别
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 15);
5、创建一个BMapGL.Point对象来表示标记点的位置
const markerPoint = new BMapGL.Point(116.404, 39.915);
6、使用这个位置创建一个 Marker组件
const marker = new BMapGL.Marker(markerPoint);
7、将标记点添加到地图上
map.addOverlay(marker);
8、完整代码
import React, { useEffect, useRef } from "react";
const MapContainer: React.FC = () => {
const mapContainer = document.getElementById("mapContainer");
useEffect(() => {
const map = new BMapGL.Map(mapContainer);
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 15);
const markerPoint = new BMapGL.Point(116.404, 39.915);
const marker = new BMapGL.Marker(markerPoint);
map.addOverlay(marker);
}, []);
return <div id="mapContainer" style={{ width: "100%", height: "400px" }} />;
};
export default MapContainer;
最终效果:
9、扩展:添加多个Marker标注
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 15);
const markersData = [
{ lng: 116.404, lat: 39.915 },
{ lng: 116.414, lat: 39.915 },
{ lng: 116.424, lat: 39.915 }
];
// 循环创建标记并添加到地图上
markersData.forEach((markerData) => {
const point = new BMapGL.Point(markerData.lng, markerData.lat);
const marker = new BMapGL.Marker(point);
map.addOverlay(marker);
});
最终效果:
10、扩展:自定义图标和尺寸
使用BMapGL.Icon类来创建自定义的图标,BMapGL.Size来设置图标的尺寸
const icon = new BMapGL.Icon(“path”, new BMapGL.Size(51, 51));
const point = new BMapGL.Point(116.404, 39.915);
const marker = new BMapGL.Marker(point, { icon: icon });
map.addOverlay(marker);