注意:
在vue | react 脚手架上使用百度地图,在其相关的index.html里引入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=xA9vkHE2k0nlUbp75KvPIxt5AfA4xymb"></script>
需要在组件使用
var BMap=window.BMap;
例子:
import React, { Component } from ‘react’
export default class 1 extends Component {
componentDidMount(){
this.getAddress()
}
//获取位置
getAddress(){
//赋值
var BMap=window.BMap;
var map = new BMap.Map(this.refs.box);
var point = new BMap.Point(116.331398, 39.897445);
map.centerAndZoom(point, 12);
var geolocation = new BMap.Geolocation();
// 开启SDK辅助定位
geolocation.enableSDKLocation();
geolocation.getCurrentPosition(function (r) {
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
var mk = new BMap.Marker(r.point);
map.addOverlay(mk);
map.panTo(r.point);
console.log(r)
//ajax
alert('您的位置:' + r.point.lng + ',' + r.point.lat);
} else {
alert('failed' + this.getStatus());
}
});
}
render() {
return (
<div>
<div id="box" ref="box"></div>
</div>
)
}
}