本文介绍高德地图在vue框架中的使用方法,H5地图通用;
首先引入 “vue-amap”: “^0.5.10”,
npm install vue-amap;
然后在main.js里写入如下代码
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
// 修改下面的key值,其中key值可前往官网进行申请;
key: '',
plugin: [
'AMap.Autocomplete',
'AMap.PlaceSearch',
'AMap.Scale',
'AMap.OverView',
'AMap.ToolBar',
'AMap.MapType',
'AMap.PolyEditor',
'AMap.CircleEditor',
'AMap.Geocoder'
],
// 默认高德 sdk 版本为 1.4.4
v: '1.4.4'
});
请注意,上述plugin中的AMap其实是在main文件中,给vue全局注入的对象,在自己的vue文件中 可直接使用AMap进行对象拿取。
在自己的组件中使用:
<div class="amap-wrapper">
<el-amap class="amap-box" vid="amap-vue" :zoom="zoom" :center="center" :plugin="plugin" :events="events">
<el-amap-marker vid="marker" :position="center" :label="label"></el-amap-marker>
</el-amap>
</div>
export default {
data() {
let self = this;
return {
zoom: 16,
address: '',
//mark的时候显示tip
label: {
content: '',
offset: [10, 12]
},
//插件集合
plugin: [
//工具条
{
pName: 'ToolBar',
positon: 'LB'
}
],
events: {
init(map) {
// 这里通过高德 SDK 完成。 如上所说AMap直接就可以取用,无须重复声明;
var geocoder = new AMap.Geocoder({
radius: 1000,
extensions: 'all',
city: '全国'
});
// 实现根据地名搜索坐标,经纬度,并地图锁定展示。
geocoder.getLocation(self.address, (status, result) => {
console.log(status, result);
if (status === 'complete' && result.geocodes.length) {
let lnglat = result.geocodes[0].location;
self.lng = lnglat.lng;
self.lat = lnglat.lat;
self.center = [self.lng, self.lat];
}
});
}
},
center: [117.070755, 38.683162],
}
created() {
const companyAddress = '山东省青岛市城阳区首创空港国际中心';
this.address = companyAddress;
this.label.content = companyAddress;
};
效果如图: