javascript - 在添加新标记之前删除添加的标记
问题描述
我正在尝试使用 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 函数中声明你的矢量图层,否则你会得到错误
推荐阅读
- sql-server - 检查表是否存在 Spark jdbc
- php - php mysql解析json utf-8编码问题
- python - Flask SQLAlchemy:AttributeError:用户查询属性为无
- javascript - 执行所有超时后如何获取数组大小
- django - settings.py 中有关 Django 电子邮件主机数据的安全问题
- reactjs - 如何动态设置初始状态?
- python - 如何从 django 中另一个对象列表的查询集中获取对象
- docker - 无法在 Bitbucket 管道中构建 docker 映像
- javascript - 茉莉花的Javascript
- json - 如何从函数中检索返回值/对象并使用 react-redux 存储在变量中?