I have a gray layer to display multiple polygons on the Mapbox map. I'm attempting to change the color of only one of them when the user clicks on it to display the "selected" the polygon. I don't want interaction, that's why I'm not using the Draw library, just to show the selected polygon.
Is there any way to do it in just one layer?? I tried adding a boolean
property called "selected" to each polygon property, but I didn't achieve to update the layer.
// Define polygons with properties
var features = [];
areas.forEach(area => features.push(turf.polygon(area.polygon, { id_area: area.id_area, name: area.name, selected: 'false' })));
features = turf.featureCollection(features);
map.on('load', function () {
// Add polygons to map
map.addSource('areas', {
'type': 'geojson',
'data': features
});
// Layer settings
map.addLayer({
'id': 'polygons',
'type': 'fill',
'source': 'areas',
'paint': {
'fill-color': [
'match',
['get', 'selected'],
'true', '#64bdbb', // if selected true, paint in blue
'#888888' // else paint in gray
],
'fill-opacity': 0.4
},
'filter': ['==', '$type', 'Polygon']]
});
});
// Click on polygon
map.on('click', 'polygons', function (e) {
if(e.features.length) {
var feature = e.features[0];
if (feature.properties.id_area == id) {
feature.properties.selected = 'true';
} else {
feature.properties.selected = 'false';
}
// How can I update the layer here to repaint polygons????
}
});
Thank you in advance!