循环遍历生成地图标记,
在每个标记的实例上绑定参数,this.markers[i].datas
然后添加到地图上
<div id="container"></div>
data() {
return {
markers:[],
map:'',
infoWindow :'',
}
},
mounted(){
//初始化地图(需提前引入高得地图的SDK: <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申请的key值"></script>)
this.map = new AMap.Map('container',{
center:[119.840498,30.266384],
zoom:14,
isHotspot:false,
features:['bg','road','building','point']
});
this.map.on('click', (ev) => {
if(this.infoWindow){
this.infoWindow.close();
}
});
//获取后端接口返回的地图标记的数据arr
arr.forEach((v,i)=>{
this.markers[i] = new AMap.Marker({
position: new AMap.LngLat(v.lng,v.lat), // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
icon:'http://qiniu.xxx.com/map.png',
anchor:'bottom-center', // 设置锚点方位
});
this.markers[i].datas=v //绑定参数,赋值到marker上
this.markers[i].on('click',this.onMarkerClick);//绑定click事件
// 将创建的点标记添加到已有的地图实例:
this.map.add(this.markers[i]);
})
},
methods: {
//2个被调用的方法
onMarkerClick(e){
console.log(e);//e.target就是被点击的Marker
this.map.setCenter(e.lnglat);//设置地图中心点
this.infoWindow = new AMap.InfoWindow({ //创建信息窗体
isCustom: true, //使用自定义窗体
content:this.info(e.target.datas), //e.target.datas获取绑定的参数
offset: new AMap.Pixel(0, -65)
});
this.infoWindow.open(this.map, e.target.getPosition());//打开信息窗体
},
info(v){ //信息窗体的内容可以是任意html片段
let str=`<div class="infowindow">
<h3>${v.name}</h3>
<p>在线车位总数: ${v.allSpaceCount}</p>
<p>实时剩余车位: ${v.remainSpaceCount}</p>
</div>`
return str
},
},