[英]Open Layers 2 Creating and adding Feature to Vector Layer from Ajax Response
[英]How to remove style from individual feature of a Vector Layer in Open Layers?
我正在学习 JS 的 OpenLayers 库。 我已经成功设置了一个单击事件来更改单个功能的样式。 但是,一旦我点击了其他地方或其他功能,我想删除该样式。
var white = [255, 255, 255, 1];
var blue = [0, 153, 255, 1];
var width = 3;
// Basic Style for the point layer
const pointStyle = new ol.style.Style({
image: new ol.style.Circle({
radius: width * 2,
fill: new ol.style.Fill({
color: blue
}),
}),
})
const map = new ol.Map({
//Some Parameters
})
const points = new ol.layer.Vector({
source: new ol.source.Vector({
url: './res/points.json',
format: new ol.format.GeoJSON(),
}),
style: pointStyle,
title: 'Points'
})
const myLayerGroup = new ol.layer.Group({
layers: [boundary, points]
})
map.addLayer(myLayerGroup);
map.on('click', function(e) {
map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
if (feature.get('Name')) {
if (feature.getStyle() == null) {
layer.setStyle(pointStyle);
feature.setStyle(); //Tried setting style to null here, didn't work
feature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: width * 2,
fill: new ol.style.Fill({
color: white //Basically points change to white here
}),
})
}))
}
}
})
})
我似乎一旦为单个元素设置了样式,即使我覆盖了整个图层的样式,单个元素的样式仍然存在。 我还没有找到一种方法来遍历每个功能并将它们各自的 styles 设置为空白。
您可以使用变量来记录更改了哪个功能
let changedFeature;
map.on('click', function(e) {
if (changedFeature)
changedFeature.setStyle();
changedFeature = undefined;
}
map.forEachFeatureAtPixel(e.pixel, function(feature, layer) {
if (feature.get('Name')) {
if (feature.getStyle() == null) {
feature.setStyle(new ol.style.Style({
image: new ol.style.Circle({
radius: width * 2,
fill: new ol.style.Fill({
color: white //Basically points change to white here
}),
})
}))
changedFeature = feature;
}
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.