如何解决删除Openlayers中的图层
我通过在OpenLayers中添加图层来添加标记。 我在asp项目中使用它,并加载了地图,并且可以添加多个图标。 现在,我加载位置并通过该图标显示它们。 我的代码是这样的:
for (var i = 0; i < loc.length; i++) {
LocationArray.push(loc[i]);
iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(loc[i])),name: 'Null Island',population: 4000,rainfall: 500
});
iconFeatures.pop();
debugger
iconFeatures.push(iconFeature);
vectorSource = new ol.source.Vector({
features: iconFeatures //add an array of features
});
iconStyle = new ol.style.Style({
image: new ol.style.Icon(({
anchor: [0.5,100],anchorXUnits: 'fraction',anchorYUnits: 'pixels',opacity: 0.8,src: '/images/icon.png',}))
});
vectorLayer = new ol.layer.Vector({
source: vectorSource,style: iconStyle
});
map.addLayer(vectorLayer);
}
现在,我想在单击该层时将其删除。 我可以检测到它被单击的位置并做出响应,但是我不知道如何删除它。 我的代码是这样的:
map.on('click',function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,function (feature) {
return feature;
});
if (feature) {
var coordinates = feature.getGeometry().getCoordinates();
if (confirm("Do you want to delete?")) {
// What should I code here?
}
} else {
// .....
}
});
解决方法
forEachFeatureAtPixel
回调也可以接收该图层,如果您保存起来很容易删除该图层:
map.on('click',function (evt) {
var vectorLayer;
var feature = map.forEachFeatureAtPixel(evt.pixel,function (feature,layer) {
vectorLayer = layer;
return feature;
});
if (feature) {
var coordinates = feature.getGeometry().getCoordinates();
if (confirm("Do you want to delete?")) {
map.removeLayer(vectorLayer);
}
} else {
// .....
}
});
,
如果要保留图层但要删除标记,可以使用clear()方法。
vectorLayer.getSource().clear();
,
感谢您的回复
我已经通过const digitGeneration = [...range(10)].map(e => e.toString());
// This is ['0','1','2','3','4','5','6','7','8','9']
代码找到了它
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。