1.安装:
npm install vue-amap --save
2.main.js引入:
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
VueAMap.initAMapApiLoader({
key: 'key',//自己申请的key
plugin: ['AMap.Scale', 'AMap.OverView', 'AMap.ToolBar', 'AMap.Geocoder','AMap.Geolocation'],
v: '1.4.4'
});
3.组件中使用:
<template>
<div class="hello">
<el-amap vid="amapDemo" :center="center" :zoom="zoom" :plugin="plugin" :events="events" class="amap-demo">
<el-amap-marker v-for="(marker, index) in markers" :position="marker.position" :events="marker.events" :visible="marker.visible"
:draggable="marker.draggable" :vid="index"></el-amap-marker>
</el-amap>
<p>当前经纬度:{{center}}</p>
<p>当前地址:{{formattedAddress}}</p>
</div>
</template>
<script>
export default {
data: function() {
let self = this
return {
//当前位置
formattedAddress:"",
zoom: 12,
//当前经纬度
center: [106.354928, 29.613256],
markers: [{
position: [106.354928, 29.613256],
events: {
click: () => {
},
dragend: (e) => {//拖拽点标记
// 设置点标记经纬度
self.markers[0].position = [e.lnglat.lng, e.lnglat.lat];
// 设置地图中心经纬度
self.center = [e.lnglat.lng, e.lnglat.lat];
// 调用逆解码函数
self.getaddress(self.center)
}
},
visible: true,
draggable: true,
template: '<span>1</span>',
}],
events: {
init: (o) => {
},
'moveend': () => {},
'zoomchange': () => {},
'click': (e) => {//点击地图
// 设置点标记经纬度
self.markers[0].position = [e.lnglat.lng, e.lnglat.lat];
// 设置地图中心经纬度
self.center = [e.lnglat.lng, e.lnglat.lat];
// 调用逆解码函数
self.getaddress(self.center)
}
},
plugin: [{
pName: 'Geolocation',
events: {
init(o) {
// o 是高德地图定位插件实例
o.getCurrentPosition((status, result) => {
if (result && result.position) {
self.lng = result.position.lng;
self.lat = result.position.lat;
self.center = [self.lng, self.lat];
self.markers[0].position = self.center;
self.loaded = true;
self.$nextTick();
}
});
}
}
},
{
pName: 'Geocoder',
events: {
init(o) {
//定位第一次逆解码
o.getAddress(self.center, (status, result) => {
if (status === 'complete' && result.info === 'OK') {
self.formattedAddress=result.regeocode.formattedAddress
}
})
}
}
}
]
};
},
methods: {
//逆解码函数
getaddress: function(lnglat) {
let self=this
AMap.plugin('AMap.Geocoder', function() {
var geocoder = new AMap.Geocoder({
// city 指定进行编码查询的城市,支持传入城市名、adcode 和 citycode
city: '010'
})
geocoder.getAddress(lnglat, function(status, result) {
if (status === 'complete' && result.info === 'OK') {
self.formattedAddress=result.regeocode.formattedAddress
// result为对应的地理位置详细信息
}
})
})
}
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped="scoped">
.hello {
height: 300px;
}
</style>