第一步使用百度地图API,可以考虑安装vue-baidu-map
这个第三方库来简化操作
npm install vue-baidu-map --save
第二步 在main.js文件内引入
import Vue from 'vue'
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: 'your_app_key' // 替换成你自己的百度地图开发密钥
})
第三步使用
完整实例:
<template>
<div>
<baidu-map @ready="getCurrentCity">
<!-- 这里是你的页面内容 -->
<button @click="getCurrentCity">获取当前城市</button>
<p>当前城市:{{ currentCity }}</p>
</baidu-map>
</div>
</template>
<script>
export default {
data() {
return {
currentCity: ''
}
},
methods: {
getCurrentCity({ BMap }) {
const geolocation = new BMap.Geolocation();
geolocation.getCurrentPosition((result) => {
if (geolocation.getStatus() === 0) {
const city = result.address.city;
this.currentCity = city;
} else {
this.currentCity = '定位失败'
}
});
}
}
}
</script>
在这个例子中,我们使用<baidu-map>
标签将页面内容包裹起来,并在@ready
事件中调用getCurrentCity
方法来获取当前城市定位。在getCurrentCity
方法中,我们使用百度地图API的Geolocation
对象来获取当前位置信息,并将获取到的城市信息赋值给currentCity
变量。