安装高德地图
npm i @amap/amap-jsapi-loader --save
引入
import AMapLoader from '@amap/amap-jsapi-loader';
*在组件中引入设置安全密匙
beforeMount() {
window._AMapSecurityCosnfig = {
securityJsCode: "XXXXXXXXXXX"
}
},
初始化
initMap(){
AMapLoader.load({
key:"XXXXXXXXXX",
version:"2.0",
plugins:[
'AMap.Scale',
'AMap.ToolBar',
'AMap.ControlBar',
'AMap.Geocoder',
'HawkEye'
],
AMapUI: {
version: '1.1',
plugins:[
'overlay/SimpleMarker',
],
},
Loca:{
version: '2.0'
},
}).then((AMap)=>{
this.map = new AMap.Map("MapSetCom",{
viewMode:"3D",
zoom:5,
resizeEnable: true,
center:[105.602725,37.076636],
});
this.map.setDefaultCursor("pointer");
this.map.addControl(new AMap.Scale());
this.map.addControl(new AMap.ToolBar());
this.map.addControl(new AMap.ControlBar());
}).catch(e=>{
console.log(e);
})
},
mounted(){
this.initMap();
},
逆编码的使用
const geocoder= new AMap.Geocoder({})
geocoder.config.jscode=this.jsCode
const lnglat=[this.getLng,this.getLat]
geocoder.getAddress(lnglat, (status, result)=> {
if (status === 'complete'&&result.regeocode) {
const address = result.regeocode.formattedAddress
this.$emit('getLonglat',this.getLng,this.getLat,address)
}else{
this.$emit('getLonglat',this.getLng,this.getLat,'根据经纬度查询地址失败')
console.error('根据经纬度查询地址失败')
}
})
使用POI搜索功能
new AMapUI.loadUI(['misc/PoiPicker'], (PoiPicker)=> {
const poiPicker = new PoiPicker({
city:'全国',
input: 'searchInput',
placeSearchOptions: {
map: this.map,
pageSize: 4
},
searchResultsContainer: 'searchResults'
})
poiPicker.citysearch.config.jscode=this.jsCode
poiPicker.on('poiPicked', (poiResult)=> {
poiPicker.hideSearchResults();
const source = poiResult.source,
poi = poiResult.item
poiPicker.searchByKeyword(poi.name);
this.map.setZoomAndCenter(18, poiResult.item.location)
if (source === 'search') {
const addressName=poi.pname+poi.cityname+poi.adname+poi.address
const lng=poi.location.lng
const lat=poi.location.lat
this.$emit('getLonglat',lng,lat,addressName)
}else if(source === 'suggest'){
const addressName=poi.district+poi.address
const lng=poi.location.lng
const lat=poi.location.lat
this.$emit('getLonglat',lng,lat,addressName)
}
})
})
点击地图创建marker点获取经纬度
this.map.on('click', (e)=> {
if(this.marker){
this.map.remove(this.marker)
}
this.getLng=e.lnglat.getLng()
this.getLat=e.lnglat.getLat()
console.log(e.lnglat.getLng(),e.lnglat.getLat())
this.marker = new AMap.Marker({
draggable: false,
cursor: 'pointer',
raiseOnDrag: true,
})
this.marker.setPosition([e.lnglat.getLng(),e.lnglat.getLat()]);
this.map.add(this.marker);
})
})