你可以在點(diǎn)擊地圖標(biāo)注之前使用 clearMarkers
方法清除上一個(gè)標(biāo)注的坐標(biāo)點(diǎn),該方法會(huì)清空地圖上所有的標(biāo)注點(diǎn)。
示例代碼:
<template>
<div id="map"></div>
</template>
<script>
import 'ol/ol.css';
import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import Point from 'ol/geom/Point';
import { Icon, Style } from 'ol/style';
export default {
name: 'Map',
data() {
return {
map: null,
source: null,
layer: null,
markers: []
};
},
mounted() {
this.initMap();
},
methods: {
initMap() {
// 初始化地圖
this.map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 2
})
});
// 添加標(biāo)注圖層
this.source = new VectorSource();
this.layer = new VectorLayer({
source: this.source
});
this.map.addLayer(this.layer);
// 監(jiān)聽地圖單擊事件
this.map.on('singleclick', this.handleMapClick);
},
handleMapClick(event) {
// 清除上一個(gè)標(biāo)注點(diǎn)
this.clearMarkers();
// 獲取點(diǎn)擊坐標(biāo)點(diǎn)
const coord = event.coordinate;
// 創(chuàng)建標(biāo)注點(diǎn)
const marker = new Feature({
geometry: new Point(coord)
});
// 設(shè)置標(biāo)注圖標(biāo)
marker.setStyle(
new Style({
image: new Icon({
src: '/../assets/logo.png',
scale: 0.5
})
})
);
// 添加標(biāo)注點(diǎn)到圖層上
this.source.addFeature(marker);
// 保存標(biāo)注點(diǎn)
this.markers.push(marker);
},
clearMarkers() {
// 清空所有的標(biāo)注點(diǎn)
this.source.clear();
this.markers = [];
}
}
};
</script>
<style scoped>
#map {
width: 100%;
height: 100vh;
}
</style>