1、安装引入高德地图,在需要的页面引入
npm i @amap/amap-jsapi-loader --save
npm install --save amap
import AMapLoader from '@amap/amap-jsapi-loader';
import Amap from 'amap';
2、在pbulic 下的index.html 文件里引入高德JSAPI 及UI组件
<script type="text/javascript">
window._AMapSecurityConfig = {
securityJsCode:'申请的密钥',
}
</script>
<!--引入高德地图JSAPI -->
<script src="//webapi.amap.com/maps?v=2.0&key=申请的key"></script>
<!--引入UI组件库(1.1版本高德) -->
<script src="//webapi.amap.com/ui/1.1/main.js"></script>
3、写id="container" 的页面容器
<el-button type="primary" style="margin-left:60px;" @click="confirmPosition">点击确认位置</el-button>
<div id="container" tabindex="10" class="mapContainer">
<div id="pickerBox">
<input id="pickerInput" placeholder="输入关键字选取地点" />
<div id="poiInfo"></div>
</div>
</div>
4、在created里调用初始化
//<***********高德地图**********>
//设置DomLibrary,jQuery或者Zepto
AMapUI.setDomLibrary($);
var that=this
//加载PositionPicker,loadUI的路径参数为模块名中 'ui/' 之后的部分
AMapUI.loadUI(['misc/PositionPicker','misc/PoiPicker'], function(PositionPicker,PoiPicker) {
var map = new AMap.Map('container',{
zoom:16,
center:[117.227308,31.820571]
})
var positionPicker = new PositionPicker({
mode:'dragMap',//设定为拖拽地图模式,可选'dragMap'、'dragMarker',默认为'dragMap'
map:map//依赖地图对象
});
//TODO:事件绑定、结果处理等
positionPicker.on('success', function(positionResult) {
console.log('成功',positionResult);
that.positionResult=positionResult
console.log('this.positionResult 11=',that.positionResult);
});
positionPicker.on('fail', function(positionResult) {
console.log('失败',positionResult);
that.$notify.error({
title: "提示",
message: "选取失败,请重新加载",
showClose: true,
});
});
//开启拖拽选址
positionPicker.start();
// <************ 地址搜索开始 ************>
var poiPicker = new PoiPicker({
//city:'北京',
input: 'pickerInput'
});
//初始化poiPicker
poiPickerReady(poiPicker);
function poiPickerReady(poiPicker) {
window.poiPicker = poiPicker;
var marker = new AMap.Marker();
var infoWindow = new AMap.InfoWindow({
offset: new AMap.Pixel(0, -20)
});
//选取了某个POI
poiPicker.on('poiPicked', function(poiResult) {
var source = poiResult.source,
poi = poiResult.item,
info = {
source: source,
id: poi.id,
name: poi.name,
location: poi.location.toString(),
address: poi.address
};
marker.setMap(map);
marker.setPosition(poi.location);
map.setCenter(marker.getPosition());
map.remove(marker)
});
}
},
);
5、按钮点击确定所选位置
//确认地图位置
confirmPosition(){
var that = this
that.merchantInfo.longitude=that.positionResult.position.lng
that.merchantInfo.latitude=that.positionResult.position.lat
that.merchantInfo.storePlace=that.positionResult.address
that.merchantInfo.storeLocation=that.positionResult.nearestJunction
},
6、容器样式
.mapContainer{
width:700px;
height:400px;
margin-left: 60px;
}
#pickerBox {
position: absolute;
z-index: 9999;
top: 10px;
right: 5px;
width: 220px;
}
#pickerInput {
width: 200px;
padding: 5px 5px;
}
#poiInfo {
background: #fff;
}
.amap_lib_placeSearch .poibox.highlight {
background-color: #CAE1FF;
}
.amap_lib_placeSearch .poi-more {
display: none!important;
}
7、效果