index.html 引入
<script type="text/javascript" src="//api.map.baidu.com/api?v=3.0&ak=xxxx"></script>
webpack.config.js 配置引入
externals: { // QMap: "qq.maps", BMap: "BMap", },
页面中引入
import BMap from "BMap";
方法中使用:
componentDidMount() {
console.log("SignMap");
//定时函数为了防止初始化报错
setTimeout(() => {
this.initMap();
}, 10);
}
initMap = () => {
var map = new BMap.Map("allmap", { enableMapClick: false });
this.setState({ map: map });
var point = new BMap.Point(116.404, 39.915); // 创建点坐标
map.centerAndZoom(point, 15);
this.getLocation(map);
};
getLocation = (map) => {
// only useful when ip localhost is disable
//获取当前位置的方法,注意只有使用ip访问页面的时候才有效,localhost不行。
var geolocation = new BMap.Geolocation();
var self = this;
geolocation.getCurrentPosition(function (r) {
console.log("获取当前位置", r);
if (r) {
self.setState({ currentLocation: r });
}
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
console.log("获取当前位置", r);
var mk = new BMap.Marker(r.point);
mk.addEventListener("click", (e) => {
console.log("clickclick", e);
self.openInfoWindow(map, r.point, "当前位置", r.address.city);
});
map.addOverlay(mk);
map.panTo(r.point);
console.log("您的位置:" + r.point.lng + "," + r.point.lat);
} else {
console.log("获取当前位置", this.getStatus());
}
});
};