引入百度地图插件
<script src="https://api.map.baidu.com/api?v=3.0&type=webgl&ak=申请的key&s=1"></script>
添加 ts 类型
declare const BMapGL: any
实现
import { useEffect, useRef } from 'react';export default () => {const mapRef = useRef<any>(null);const creatMarker = (list: { gps: number[]; title: string; icon: string }[]) => {mapRef?.current?.clearOverlays(); // 先清除后创建,适用于切换list?.forEach((item) => {// 创建图标const myIcon = new BMapGL.Icon(item.icon, new BMapGL.Size(40, 50), {anchor: new BMapGL.Size(20, 50),});// 创建Marker标注,使用图标const point = new BMapGL.Point(item.gps[0], item.gps[1]);const marker = new BMapGL.Marker(point, {icon: myIcon,});// 点标记添加点击事件const infoWindow = new BMapGL.InfoWindow(item, {width: 200,height: 100,title: item.title,});marker.addEventListener('click', () => {mapRef.current.openInfoWindow(infoWindow, point); // 开启信息窗口});// 将标注添加到地图mapRef.current.addOverlay(marker);});};// 设置行政区划const getBoundary = () => {const bdary = new BMapGL.Boundary();bdary.get('东阳', (rs: any) => {// 获取行政区域const count = rs.boundaries.length; // 行政区域的点有多少个if (count === 0) {console.log('未能获取当前输入行政区域');return;}let pointArray: any[] = [];for (let i = 0; i < count; i += 1) {const ply = new BMapGL.Polygon(rs.boundaries[i], {strokeWeight: 2,strokeColor: '#ff0000',}); // 建立多边形覆盖物mapRef.current.addOverlay(ply); // 添加覆盖物pointArray = pointArray.concat(ply.getPath());}mapRef.current.setViewport(pointArray); // 调整视野});};const creatMap = () => {mapRef.current = new BMapGL.Map('my-map');mapRef.current.enableScrollWheelZoom(true);mapRef.current.centerAndZoom(new BMapGL.Point(120.325301, 29.159552), 16);// mapRef.current.setMapStyleV2({ styleJson }); // 设置地图主题 https://lbsyun.baidu.com/apiconsole/custommapcreatMarker([{title: '标记一',icon: 'https://xxx.png',gps: [120.3202894172981, 29.1566923548061],},{title: '标记二',icon: 'https://xxx2.png',gps: [120.3202894177781, 29.1566966648061],},]);// getBoundary();};useEffect(() => {creatMap();}, []);return <div id="my-map" style={{ width: 500, height: 500 }} />;};
方法
如何清除地图上的覆盖物?
清除地图上所有的标记,用 map.clearOverlays();
清除单个标注 iMarker,用 map.removeOverlay(iMarker);
显示和隐藏自定义覆盖物,可以继承 overlay 的 hide(); 或者 show() 方法。
// 创建 Marker 标注const point = new BMapGL.Point(it.GPS[0], it.GPS[1]);const marker = new BMapGL.Marker(point, {icon: 'https://xxx.png',});// 隐藏、显示 markermarker.hide();marker.show();
