需求
在頁(yè)面中實(shí)現(xiàn)地圖選點(diǎn)功能(包括輸入位置標(biāo)記點(diǎn)薄声,地圖點(diǎn)擊標(biāo)記點(diǎn)题画,標(biāo)記點(diǎn)需要有經(jīng)度苍息、緯度和詳細(xì)地址)
思路分析
1.先實(shí)現(xiàn)輸入位置竞思,獲取經(jīng)緯度,實(shí)現(xiàn)地圖標(biāo)記點(diǎn)铃肯;
2.監(jiān)聽地圖點(diǎn)擊事件,獲取經(jīng)緯度步藕,實(shí)現(xiàn)地圖標(biāo)記點(diǎn);
準(zhǔn)備工作
1.vue-amap文檔
2.高德地圖JS API沾歪、高德地圖輸入提示灾搏、高德地圖逆地理編碼
代碼使用
1.安裝
amap
npm install vue-amap --save
2.
main.js
引用
// 引入vue-amap(高德地圖)
import VueAMap from 'vue-amap';
Vue.use(VueAMap);
// 初始化vue-amap
VueAMap.initAMapApiLoader({
// 高德的key
key: '高德地圖申請(qǐng)的key',
// 插件集合
plugin: [
'AMap.Autocomplete',
'AMap.PlaceSearch',
'AMap.Scale',
'AMap.OverView',
'AMap.ToolBar',
'AMap.MapType',
'AMap.PolyEditor',
'AMap.CircleEditor',
'AMap.Geolocation'
],
// 高德 sdk 版本,默認(rèn)為 1.4.4
v: '1.4.4'
});
3.
vue文件
代碼
<template>
<div class="amap-page-container">
<!--使用element UI作為輸入框-->
<el-input v-model="mapInfo.address" placeholder="請(qǐng)輸入內(nèi)容" id="tipinput"></el-input>
<el-amap
vid="amapDemo"
:center="mapInfo.lnglat"
:amap-manager="amapManager"
:zoom="zoom"
:events="events"
class="amap-demo"
style="height: 300px"
>
<el-amap-marker ref="marker" vid="component-marker" :position="mapInfo.lnglat"></el-amap-marker>
</el-amap>
<p>標(biāo)記點(diǎn):{{ mapInfo.address }}媳板,經(jīng)度:{{ mapInfo.lng }}蛉幸,緯度:{{ mapInfo.lat }}</p>
</div>
</template>
<style>
.amap-demo {
height: 300px;
}
</style>
<script>
import { AMapManager } from 'vue-amap';
const amapManager = new AMapManager();
export default {
data: function () {
return {
mapInfo: {
//初始值默認(rèn)為天安門
address: '北京市東城區(qū)東華門街道天安門',
lng: 116.397451,
lat: 39.909187,
lnglat: [116.397451, 39.909187]
},
zoom: 12,
amapManager,
events: {
click: (e) => {
this.mapInfo.lng = e.lnglat.lng;
this.mapInfo.lat = e.lnglat.lat;
this.mapInfo.lnglat = [e.lnglat.lng, e.lnglat.lat];
this.getFormattedAddress();
}
}
};
},
methods: {
getFormattedAddress() {
AMap.plugin('AMap.Geocoder', () => {
let GeocoderOptions = {
city: '全國(guó)'
};
let geocoder = new AMap.Geocoder(GeocoderOptions);
geocoder.getAddress(this.mapInfo.lnglat, (status, result) => {
console.log('通過(guò)經(jīng)緯度拿到的地址', result);
if (status === 'complete' && result.info === 'OK') {
this.mapInfo.address = result.regeocode.formattedAddress;
} else {
this.mapInfo.address = '無(wú)法獲取地址';
}
});
});
},
initMapByInput() {
AMap.plugin('AMap.Autocomplete', () => {
let autoOptions = {
city: '全國(guó)',
input: 'tipinput'
};
let autoComplete = new AMap.Autocomplete(autoOptions);
AMap.event.addListener(autoComplete, 'select', (e) => {
console.log('通過(guò)輸入拿到的地址', e);
this.mapInfo.lat = e.poi.location.lat;
this.mapInfo.lng = e.poi.location.lng;
this.mapInfo.lnglat = [e.poi.location.lng, e.poi.location.lat];
this.getFormattedAddress();
});
});
}
},
mounted() {
this.initMapByInput();
}
};
</script>
<style>
#tipinput {
margin-bottom: 10px;
}
</style>
運(yùn)行結(jié)果
image.gif