1、先到百度地图申请你的ak,然后将“地址白名单”设置为一个*号,否则本地环境测试的时候会报错。
2、本地测试的话,就到index.html加入
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=你的ak"></script>
等到上生产环境则需要将其改为
<script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=你的AK&s=1"></script>
3、先npm一个babel-polyfill
npm install --save babel-polyfill
到webpack.base.conf.js添加externals
entry: {
// app: './src/main.js'
app: ['babel-polyfill', './src/main.js']//兼容IE
},
externals: { //这是加入的那一行
"BMap":"BMap"
},
4、使用页面,先引入BMap(记得不要在mounted之前的生命周期使用,不然BMap undefined)
import BMap from 'BMap'
data(){
return{
creditLongitude: 0,
creditLatitude: 0
}
}
mounted() {
let _this = this
var geolocation = new BMap.Geolocation()
geolocation.getCurrentPosition(function(r) {
console.log(r)
if (this.getStatus() == BMAP_STATUS_SUCCESS) {
const myGeo = new BMap.Geocoder()
myGeo.getLocation(new BMap.Point(r.point.lng, r.point.lat), data => {
if (data.addressComponents) {
let location = {lat:r.point.lat, lng:r.point.lng}
_this.$store.commit("location",location)//这个是保存到vuex的,没有可以不做
sessionStorage.setItem('location',JSON.stringify(location))
}
})
}
})
},
//vuex使用时,当然这里我封装过了,有兴趣的可以找下我vue分类的vuex封装
this.$store.state.location.lng