一.循环渲染点位
如图所示,紫色点位为动态循环点位
首先,我们请求完接口,返回点位
这里是全部代码 下方有拆分讲解
this.map.remove(this.marks)
this.marks = []
this.map.plugin(['AMap.PlaceSearch'], () => {
var PlaceSearchOptions = { //设置PlaceSearch属性
city: "武汉", //城市
type: "", //数据类别
pageSize: 10, //每页结果数,默认10
pageIndex: 1, //请求页码,默认1
extensions: "base" //返回信息详略,默认为base(基本信息)
};
var MSearch = new this.amap.PlaceSearch(PlaceSearchOptions); //构造PlaceSearch类
this.amap.Event.addListener(MSearch, "complete", (res) => {
if (res.poiList.pois && res.poiList.pois.length) {
this.map.setZoomAndCenter(15, [res.poiList.pois[0].location.lng, res.poiList.pois[0].location.lat])
res.poiList.pois.forEach(item => {
let marker = new this.amap.Marker({
position: [item.location.lng, item.location.lat],
icon: new this.amap.Icon({
image: require("@/assets/ple.png"),
})
})
this.marks.push(marker)
marker.on('click', () => {
twParkingInfo({
longitude: item.location.lng,
latitude: item.location.lat
}).then(({ data }) => {
this.praking = data.data
this.isShow = true
this.marks.forEach((item, index) => {
item.setIcon(new this.amap.Icon({
image: require("@/assets/ple.png"),
}))
})
marker.setIcon(new this.amap.Icon({
image: require("@/assets/cs.png"),
}))
this.map.setZoomAndCenter(15, [item.location.lng, item.location.lat])
})
})
this.map.add(marker);
});
}
}); //返回结果
MSearch.search(this.input); //关键字查询
});
这里我调用了高德的查询 API 搜索后点击搜索按钮事件 循环高德返回点位
循环添加点位
res.poiList.pois.forEach(item => {
let marker = new this.amap.Marker({
position: [item.location.lng, item.location.lat],
icon: new this.amap.Icon({
image: require("@/assets/ple.png"),
})
})
this.map.add(marker);
});
二.定义数组接受新增点位
在 data 里面定义一个数组 我的叫 marks
这里在循环的时候将新增的 marker 全都 push 到 marks 中
this.marks.push(marker)
这里添加到数组里有两点好处
1. 便于下次搜索添加新点位之前 清除掉上次搜索增加点位
this.map.remove(this.marks) // 清除点位
this.marks = []
所以每次调用查询方法时 将之前增加点位移除 并将该数组清空
2. 便于修改图标
marker.on('click', () => {
// 每次点击 将点位数组循环 将图标修改成统一图标
this.marks.forEach((item, index) => {
item.setIcon(new this.amap.Icon({
image: require("@/assets/ple.png"),
}))
})
// 然后单独修改点击点位图标 即可
marker.setIcon(new this.amap.Icon({
image: require("@/assets/cs.png"),
}))
this.map.setZoomAndCenter(15, [item.location.lng, item.location.lat])
})