前言
在很多项目中,我们会经常用到地图展示,目前主流的地图开发API:百度地图、高德地图、腾讯地图。今天我们讲一下,在vue项目中如何使用高德地图,常用的:信息弹窗、坐标定位,拾取坐标等功能
引入
在main.js中引入
import AMap from 'vue-amap'
Vue.use(AMap);
AMap.initAMapApiLoader({
key: 'xxxxxxx',
plugin: ['AMap.Geolocation','MarkerClusterer','AMap.Heatmap','AMap.Geocoder'],
v: '1.4.4',
uiVersion: '1.0.11'
});
前端页面
<div :id="mapId" class="myt-map"></div>
data() {
let self = this
return {
mapId: 'myt-map',
mapInst: '',
centerMarker: '',
showInfoWindow: false,
infoWindow: {},
address: null,
searchKey: '',
loaded: false,
center: [117.11084,36.697535],
}
},
mounted() {
var _this = this
this.mapInst = new AMap.Map(this.mapId, {
center: this.center, //中心点坐标
zoom: 4, //zooms: [7.7, 20],
})
this.gatwayList();
},
methods: {
setInfoWindows(e) {
// 此时需要把组件的样式设置为可见
this.showInfoWindow = true
// 设置marker头部的标题信息窗口
const infoWindow = new AMap.InfoWindow({
isCustom: true, // 使用自定义窗体
content: this.$refs['infoWindow'].$el, // 只有当组件渲染完毕后,通过$el才能拿到原生的dom对象
offset: new AMap.Pixel(-9, -60), // 设置定位偏移量
})
this.infoWindow = infoWindow
// 信息窗口打开
this.infoWindow.open(this.mapInst, e.target.getPosition()) //后面的参数指的是经纬度,在此显示窗口
},
changeMarkerStyle(location) {
// 1正常 2异常
if (location.status === 1) {
return `<div style="width: 10px;height: 10px;background: #3AB236;border-radius: 50%;"></div>`
}
return `<div style="width: 14px;height: 14px;background: #EC4646;border-radius: 50%;"></div>`
},
//获取网关数据
gatwayList(){
let vm = this
list().then((res)=>{
res.data.data.forEach(function(v,i){
// vm.markers.push([ v.lng, v.lat])
var marker = new AMap.Marker({
position: [ v.lng, v.lat],
// content: vm.changeMarkerStyle(v.id),
offset: new AMap.Pixel(-13, -30),
})
// 标记上绑定上点击事件
marker.on('click', (e) => {
// 点击后创建自定义信息窗口
//实例化信息窗体
var infoWindow = new AMap.InfoWindow({
isCustom: true, //使用自定义窗体
content: vm.createInfoWindow(v),
offset: new AMap.Pixel(16, -45)
});
infoWindow.open(vm.mapInst, marker.getPosition());
})
marker.setMap(vm.mapInst)
})
})
},
//构建自定义信息窗体
createInfoWindow(v) {
var html="<div class="del-div">\n" +
" <div class="box-card">\n" +
" <div class="content_box">\n" +
" <div class="title">\n" +
" <span>"+v.name+"</span>\n" +
" </div>\n" +
" <div class="mark_name margin-top-20 margin-bottom-20">\n" +
" <div class="mark">\n" +
" <span>状态:正常</span>\n" +
" </div>\n" +
" </div>\n" +
" <div class="bottom_btn">\n" +
" <div class="btn_big margin-right-10">\n" +
" <span>编辑</span>\n" +
" </div>\n" +
" <div class="btn_big">\n" +
" <span>查看</span>\n" +
" </div>\n" +
" </div>\n" +
" </div>\n" +
" </div>\n" +
" <!-- </el-card> -->\n" +
" </div>"
return html;
},
//关闭信息窗体
closeInfoWindow() {
this.mapInst.clearInfoWindow();
},