Change a Layer Color
Call map.setPaintProperty() to change a paint value live. Here three buttons set the fill color of a polygon layer.
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: [13.405, 52.52], zoom: 11 }); // Berlin
const area = { type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [[[13.33, 52.55], [13.48, 52.55], [13.48, 52.49], [13.33, 52.49], [13.33, 52.55]]] } };
map.on('load', function () {
map.addSource('area', { type: 'geojson', data: area });
map.addLayer({ id: 'area', type: 'fill', source: 'area', paint: { 'fill-color': '#1a73e8', 'fill-opacity': 0.6 } });
document.querySelectorAll('.btns button').forEach(function (b) {
b.addEventListener('click', function () { map.setPaintProperty('area', 'fill-color', b.getAttribute('data-color')); });
});
});
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%; }
.btns { position:absolute; top:10px; left:10px; z-index:1; }
.btns button { margin:2px; padding:6px 10px; border:none; border-radius:4px; color:#fff; cursor:pointer; font:13px system-ui,sans-serif; }
</style>
</head>
<body>
<div class="btns"><button data-color="#1a73e8" style="background:#1a73e8">Blue</button><button data-color="#e8551a" style="background:#e8551a">Orange</button><button data-color="#0a8754" style="background:#0a8754">Green</button></div>
<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: [13.405, 52.52], zoom: 11 }); // Berlin
const area = { type: 'Feature', properties: {}, geometry: { type: 'Polygon', coordinates: [[[13.33, 52.55], [13.48, 52.55], [13.48, 52.49], [13.33, 52.49], [13.33, 52.55]]] } };
map.on('load', function () {
map.addSource('area', { type: 'geojson', data: area });
map.addLayer({ id: 'area', type: 'fill', source: 'area', paint: { 'fill-color': '#1a73e8', 'fill-opacity': 0.6 } });
document.querySelectorAll('.btns button').forEach(function (b) {
b.addEventListener('click', function () { map.setPaintProperty('area', 'fill-color', b.getAttribute('data-color')); });
});
});
map.addControl(new MaptoolkitLogoControl());
</script>
</body>
</html>