[英]Remove added marker before adding new marker
我正在嘗試使用 openlayers 開發具有標簽位置功能的 Web 應用程序。 我想在單擊時添加最多一個標記來映射。 當用戶第二次點擊地圖時,之前的標記將被刪除。 但是,在添加新標記之前,我找不到合適的方法來刪除標記。
<script type="text/javascript">
var myMap = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([118.0149, -2.5489]),
zoom: 5
})
});
var features = [];
myMap.on('click', function(evt) {
var coordinates = evt.coordinate;
var lonlat = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
var lon = lonlat[0];
var lat = lonlat[1];
var Markers = {lat: lat, lng: lon};
addPin(Markers);
});
function addPin(Markers) {
var item = Markers;
var longitude = item.lng;
var latitude = item.lat;
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([longitude, latitude], 'EPSG:4326', 'EPSG:3857'))
});
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5, 1],
src: "http://cdn.mapmarker.io/api/v1/pin?text=P&size=50&hoffset=1"
}))
});
iconFeature.setStyle(iconStyle);
features.push(iconFeature);
var vectorSource = new ol.source.Vector({
features: features
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
myMap.addLayer(vectorLayer);
}
你有幾種方法可以做到這一點。 最正確的方法是使用:
vectorLayer.getSource().clear();
或者:
vectorSource.clear();
但是在您的情況下,每次添加標記時,您也會添加一個新圖層,只需在添加之前從地圖中刪除圖層就足夠了:
var vectorLayer;
function addPin(Markers) {
//here it is
myMap.removeLayer(vectorLayer)
var item = Markers;
var longitude = item.lng;
var latitude = item.lat;
.........................
.........................
//and here remove the keyword var , so init the one declared in global section
vectorLayer = new ol.layer.Vector({
source: vectorSource
});
不要忘記在全局部分而不是在 addPin 函數中聲明你的矢量圖層,否則你會得到錯誤
如果您只想獲取標記的當前位置,我建議您不要將以前的值保存在特征數組中。 這是 JS fiddle 的基本解決方案。
在你的addPin
函數中改變這個
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
您可以在此處查看工作副本https://jsfiddle.net/shahhassancs/xgw5jus7/4/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.