注意:
在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>
)
}
}
本文介绍如何在Vue或React项目中使用百度地图API。通过在index.html文件中引入必要的地图脚本,然后在组件中利用window.BMap变量进行地图初始化,可以实现地图显示及位置获取等功能。示例代码展示了地图中心设置、缩放级别调整以及当前位置获取的具体实现。
958

被折叠的 条评论
为什么被折叠?



