While @nucleon's answer works, if you want to let users toggle layer's visibility on and off, setting visibility
to visible
can trigger unnecessary tile requests to the server, even for layers already loaded into the map.
To avoid that, I keep layers visible all the time and toggle their visibility by setting opacity
to 0
(invisible) or 1
(to make them visible again).
Note that a layer must be initially loaded before its visibility can be toggled:
// [email protected]
const show = true;
const layers = map.getStyle().layers;
layers
// Filter for symbol layers with "-label" suffix (modify as needed)
.filter(layer => layer.type === 'symbol' && layer.id.includes('-label'))
.forEach(layer => map.setPaintProperty(layer.id, 'text-opacity', show ? 1 : 0));