[英]How to remove style from individual feature of a Vector Layer in Open Layers?
I'm learning the OpenLayers library of JS.我正在学习 JS 的 OpenLayers 库。 I have successfully set a click event to change the style of an individual feature.
我已经成功设置了一个单击事件来更改单个功能的样式。 However, I want to remove the style once I have clicked somewhere else or on to other feature.
但是,一旦我点击了其他地方或其他功能,我想删除该样式。
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
}),
})
}))
}
}
})
})
I seems once I have set a style to individual element, even if I overwrite the style of whole layer, the style of the individual element still persists.我似乎一旦为单个元素设置了样式,即使我覆盖了整个图层的样式,单个元素的样式仍然存在。 I haven't found a method to loop over each feature and set their individual styles to be blank.
我还没有找到一种方法来遍历每个功能并将它们各自的 styles 设置为空白。
You can use a variable to record which feature was changed您可以使用变量来记录更改了哪个功能
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.