Skip to content

Toggle Layer Visibility

Flip the visibility layout property between visible and none with map.setLayoutProperty() to toggle a layer on and off.

import { MaptoolkitLogoControl } from 'https://cdn.jsdelivr.net/npm/@maptoolkit/maplibre-gl-logo/+esm';
const map = new maplibregl.Map({ container: 'map', attributionControl: { customAttribution: '' }, style: 'https://styles.maptoolkit.org/summer.json', center: [-3.7038, 40.4168], zoom: 11 }); // Madrid
const area = { type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [[[-3.75, 40.45], [-3.66, 40.45], [-3.66, 40.38], [-3.75, 40.38], [-3.75, 40.45]]] } };
map.on('load', function () {
  map.addSource('area', { type: 'geojson', data: area });
  map.addLayer({ id: 'area', type: 'fill', source: 'area', paint: { 'fill-color': '#e8551a', 'fill-opacity': 0.5 } });
  document.getElementById('toggle').addEventListener('click', function () {
    const v = map.getLayoutProperty('area', 'visibility');
    map.setLayoutProperty('area', 'visibility', v === 'none' ? 'visible' : 'none');
  });
});
map.addControl(new MaptoolkitLogoControl());
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/maplibre-gl.css" />
  <style>
    html, body { width: 100%; height: 100%; margin: 0; padding: 0; }
    #map { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <button id="toggle" style="position:absolute;top:10px;left:10px;z-index:1;padding:6px 10px;border:none;border-radius:4px;background:#1a73e8;color:#fff;cursor:pointer;font:13px system-ui,sans-serif">Toggle layer</button>
  <div id="map"></div>
  <script type="module">
import { MaptoolkitLogoControl } from 'https://cdn.jsdelivr.net/npm/@maptoolkit/maplibre-gl-logo/+esm';
const map = new maplibregl.Map({ container: 'map', attributionControl: { customAttribution: '' }, style: 'https://styles.maptoolkit.org/summer.json', center: [-3.7038, 40.4168], zoom: 11 }); // Madrid
const area = { type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [[[-3.75, 40.45], [-3.66, 40.45], [-3.66, 40.38], [-3.75, 40.38], [-3.75, 40.45]]] } };
map.on('load', function () {
  map.addSource('area', { type: 'geojson', data: area });
  map.addLayer({ id: 'area', type: 'fill', source: 'area', paint: { 'fill-color': '#e8551a', 'fill-opacity': 0.5 } });
  document.getElementById('toggle').addEventListener('click', function () {
    const v = map.getLayoutProperty('area', 'visibility');
    map.setLayoutProperty('area', 'visibility', v === 'none' ? 'visible' : 'none');
  });
});
map.addControl(new MaptoolkitLogoControl());
  </script>
</body>
</html>