一、在百度官网获得自己的AK(密钥)
1、获取AK地址:http://lbsyun.baidu.com/index.php?title=subway/guide/getkey
2、获得自己的AK,拼接成百度地图api
https://api.map.baidu.com/api?v=3.0&ak=这里填你自己的AK
3、当作模块导入BMap
法1、法2选一个即可,法2中给出了配置项是否暴露的两种情况,根据需要自行修改
//法1:
特别注意:注意在react中使用百度地图的API时会传入大写的变量名,这时要使用window.变量名,来表明它是全局变量,不然会报错
在React项目启动首页index.html中加上
<script>
window.BMap = BMap
</script>
如果不想使用windows.变量名,请进行如下配置:
//法2:
1、create react app创建的项目,未暴露配置项,去node_modules文件夹下找react-script>config>webpack.config.dev.js添加
externals:{
'BMap':'BMap',
'BMapLib': 'BMapLib',
}
2、如果配置项暴露,在webpack.config.js的module.exports里添加:
二、在React项目启动首页index.html的head中引入此接口
三、React中使用百度地图
1、demo
import React,{Component} from 'react'
import style from './mapdemo.module.scss';
import api from 'api'
import { Card } from 'antd';
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import BMap from 'BMap';
import BMapLib from 'BMapLib';
export default class mapdemo extends Component{
static displayName = 'mapdemo';
constructor(props) {
super(props);
this.state = {
};
this.map=null
}
componentDidMount(){
this.initMap();
}
initMap=()=>{//显示标签,创建地图实例
this.map = new BMap.Map('mapid',{
minZoom:11,
maxZoom:18
})
var point = new BMap.Point(116.418261, 39.921984)//创建坐标点
this.map.enableScrollWheelZoom(true)//启用滚轮放大缩小,默认禁用-用了过后,pop不能滚动,所以手动缩放地图
this.map.enableContinuousZoom(); //启用地图惯性拖拽,默认禁用
//this.map.enableDoubleClickZoom(true)
this.map.centerAndZoom(point, 15)// 初始化地图,设置城市和地图级别
//var maxBounds = new BMap.Bounds(new BMap.Point(this.mapcfg.maxBounds[0][1], this.mapcfg.maxBounds[0][0]),new BMap.Point(this.mapcfg.maxBounds[1][1], this.mapcfg.maxBounds[1][0])); // 范围 左下角,右上角的点位置
//BMapLib.AreaRestriction.setBounds(this.map, maxBounds); // map为中心,maxBounds为范围的地图
var marker = new BMap.Marker(point);//创建标注
this.map.addOverlay(marker);
}
render(){
return(
<div className={style.wrap}>
<div className="mapid" id="mapid"></div>
</div>
)
}
}
2、设置地图范围
需要在index.html的head中引入AreaRestriction_min.js文件
<script type="text/javascript" src="http://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js"></script>