I am trying to show or hide features on click.
I have many points with different colors, I am trying to change opacity to 0/1.
What I managed to do is set 2 different feature styles and use setStyle on click.
I can hide a feature but when I try to unhide it is styled as default OpenLayers feature. See examples here:
Picture of point when map is loaded
Picture of point when I hide it
Picture of point when I try to unhide it (I want it to be back to orange but its default style)
This is the code snippet:
selectedLayer
.getSource()
.forEachFeatureInExtent(extent, function (feature) {
if (
Object.values(Object.values(feature.get("info"))[0][2])[1] === t
) {
if (e.target.className === "menu-selector") {
feature.setStyle(style); // Apply OLD STYLE (style before hiding the feature)
}
if (e.target.className === "menu-selector2") {
var style = feature.getStyle(); // Get current style (so I can reapply it later)
feature.setStyle(
new ol.style.Style({
image: new ol.style.Circle({
radius: 0,
fill: new ol.style.Fill({
color: "rgba(0, 0, 0, 0)",
}),
stroke: new ol.style.Stroke({
color: [0, 0, 0, 0],
width: 0,
}),
}),
})
); // hide the feature
}
}
});
I found this also:
feature.getStyle().getImage().setOpacity(0);
But that function shows/hides all points with same Style, not just the selected one. For example, if I want to hide 1 feature and its a grey circle, it will hide all grey circles in extent.
feature.setStyle(feature.getStyle().clone());(you only need do it once, when changing back it is already cloned) - Mike