vue实现高德地图清除搜索结果marker
时间: 2023-09-04 10:13:06 浏览: 146
要清除高德地图的搜索结果 Marker,您可以通过以下步骤实现:
1. 在 Vue 组件中引入高德地图 JavaScript API:
```
<script src="https://webapi.amap.com/maps?v=1.4.15&key=YOUR_API_KEY"></script>
```
2. 在 `mounted` 钩子函数中初始化地图,并将地图实例保存在 `this.map` 中:
```
mounted() {
this.map = new AMap.Map('map-container', {
zoom: 13,
center: [116.397428, 39.90923]
});
}
```
3. 在搜索时,使用 `AMap.Marker` 创建 Marker,并保存在数组中:
```
search() {
// 清除之前的 Marker
this.clearMarkers();
// 搜索
AMap.plugin('AMap.PlaceSearch', () => {
const placeSearch = new AMap.PlaceSearch({
city: '北京市',
pageSize: 10,
pageIndex: 1,
map: this.map
});
placeSearch.search('餐厅', (status, result) => {
if (status === 'complete' && result.info === 'OK') {
const poiList = result.poiList;
poiList.forEach(poi => {
const marker = new AMap.Marker({
position: poi.location,
title: poi.name,
map: this.map
});
this.markers.push(marker);
});
}
});
});
},
```
4. 在清除搜索结果时,遍历 Marker 数组,调用 `setMap(null)` 方法将 Marker 从地图上移除,并清空数组:
```
clearMarkers() {
this.markers.forEach(marker => {
marker.setMap(null);
});
this.markers = [];
},
```
完整的 Vue 组件代码如下:
```
<template>
<div>
<div id="map-container"></div>
<button @click="search">搜索餐厅</button>
<button @click="clearMarkers">清除搜索结果</button>
</div>
</template>
<script>
export default {
data() {
return {
map: null,
markers: []
};
},
mounted() {
this.map = new AMap.Map('map-container', {
zoom: 13,
center: [116.397428, 39.90923]
});
},
methods: {
search() {
// 清除之前的 Marker
this.clearMarkers();
// 搜索
AMap.plugin('AMap.PlaceSearch', () => {
const placeSearch = new AMap.PlaceSearch({
city: '北京市',
pageSize: 10,
pageIndex: 1,
map: this.map
});
placeSearch.search('餐厅', (status, result) => {
if (status === 'complete' && result.info === 'OK') {
const poiList = result.poiList;
poiList.forEach(poi => {
const marker = new AMap.Marker({
position: poi.location,
title: poi.name,
map: this.map
});
this.markers.push(marker);
});
}
});
});
},
clearMarkers() {
this.markers.forEach(marker => {
marker.setMap(null);
});
this.markers = [];
},
}
};
</script>
```
阅读全文