I'm working on a method to show or hide feature labels (text) based on zoom level. I have a working example that uses setScale on the style object of the feature and is triggered by the "moveend" event of the view:
map_obj.on('moveend', function (evt) {
let m = evt.map;
let v = m.getView();
if (v.getZoom() > 10) {
toggleLabels(true);
} else {
toggleLabels(false);
}
});
function toggleLabels(show) {
let lyrs = map_obj.getAllLayers();
for (let l in lyrs) {
source = lyrs[l].getSource();
let features = source.getFeaturesCollection();
features.forEach( function (feat) {
let s = feat.getStyle()[0]; //works
if (show) {
if (s.getText().getScale()[0] == 0) {
s.getText().setScale([1, 1]);
}
} else {
if (s.getText().getScale()[0] == 1) {
s.getText().setScale([0, 0]);
}
}
});
}
map_obj.render(); //appears to do nothing
//map_obj.renderSync(); //exceeds max call stack size
}
If the user zooms above level 10, labels show up. However, when the user zooms out below level 10, the labels still show until the map is moved one more time. I'm trying to force the map to re-render but it's not working. Is there a better event to use to trigger this, or a maybe a better strategy for showing/hiding labels?