79164816

Date: 2024-11-07 02:13:05
Score: 1
Natty:
Report link

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));
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @nucleon'sworks
  • Low reputation (1):
Posted by: lekoshimura