1.npm安装
npm install vue-amap --save
2.在main.js文件中进行全局引用
//vue-amap地图插件
import VueAMap from "vue-amap";
Vue.use(VueAMap)
VueAMap.initAMapApiLoader({
key: "--------------",//高德开放平台申请的key值
plugin: [
"AMap.Autocomplete", //输入提示插件
"AMap.PlaceSearch", //POI搜索插件
"AMap.Scale", //右下角缩略图插件 比例尺
"AMap.OverView", //地图鹰眼插件
"AMap.ToolBar", //地图工具条
"AMap.Geolocation", //定位控件,用来获取和展示用户主机所在的经纬度位置
"AMap.Geocoder", // 逆地理编码,通过经纬度获取地址所在位置详细信息
// 根据需求选用
],
uiVersion: "1.0", // 地图ui版本
v: "1.4.4", // amap版本
});
先看效果图 后看代码(可随意调整,当前只满足我司需求)
3.在使用文件中引用
html
<a-form-item label="位置定位" required>
<el-amap-search-box ref="searchBoxs" class="search-box" :default="gatherDefaultValue" :search-option="gatherSearchOption" :on-search-result="gatherSearchResult">
</el-amap-search-box>
<!-- 引用地图-->
<div class="amap-wrapper">
<el-amap ref="map" vid="amap-vue" :events="gatherEvents" :center="gatherCenter" :zoom="gatherZoom" class="amap-box">
<el-amap-marker :position="gatherCenter" key="100"></el-amap-marker>
</el-amap>
</div>
</a-form-item>
js
return{
//以下为地图所用参数
gatherZoom: 18,
gatherCenter: [120, 30],//默认进去的地点
gatherSearchOption: {
// 限制搜索城市的范围
citylimit: false,
},
gatherDefaultValue: "",
searchResult: {
address: "",
latitude: "",
longitude: "",
name: "",
type: "",
country: "",
province: "",
city: "",
area: "",
township: "",
street: "",
neighborhood: "",
locationName: "",
},
gatherEvents: {
click(e) {
_this.gatherCenter = [e.lnglat.lng, e.lnglat.lat];
_this.getGatherAddress(_this.gatherCenter);
_this.gatherDefaultValue = "";
},
},
}
methods:{
//调用地图所用方法事件
gatherSearchResult(pois) {
//搜索
let latSum = 0;
let lngSum = 0;
let that = this;
if (pois && pois.length > 0) {
//如果长度为1则无需转化
let poi = pois[0];
let lng = poi["lng"];
let lat = poi["lat"];
that.gatherCenter = [lng, lat];
that.gatherZoom = 18;
that.content = poi.name;
that.searchResult.address = poi.address;
that.searchResult.latitude = poi.lat;
that.searchResult.longitude = poi.lng;
that.getGatherAddress(that.gatherCenter);
} else {
that.searchResult = [];
}
},
//集合地址
getGatherAddress(center) {
let _this = this;
let geocoder = new AMap.Geocoder({});
geocoder.getAddress(center, function (status, result) {
console.log(result,'result')
if (status === "complete" && result.info === "OK") {
// let obj = result.regeocode.addressComponent;
// let locationName =
// obj.province +
// obj.city +
// obj.district +
// obj.township +
// obj.street +
// obj.streetNumber;
// _this.form.setFieldsValue({
// gatherAddress: locationName,
// });
let obj = result.regeocode.formattedAddress;
//对搜索组件的input进行赋值
_this.$refs.searchBoxs.keyword = obj;
//最后是需要传给后端的东西,具体后端要啥穿啥就行,字段可随意更改
_this.gatherAddress= {
address:obj,
lng:center[0],
lat:center[1]
}
}
});
},
}