I have made a CARTO VL map that allows the user to update the active layer depending on which groundwater aquifer option is selected.
The layers have different Sources, but use the same Viz. For example:
const fracturedSource = new carto.source.Dataset('fractured');
const intergranularSource = new carto.source.Dataset('intergranularfractured');
const karstSource = new carto.source.Dataset('karst');
const aquiferViz = new carto.Viz(`
color: ramp($yield_ls, reverse(temps))
strokeColor: rgba(0,0,0,0.3)
strokeWidth: 1
`);
const aquiferLayer = new carto.Layer('aquiferLayer', fracturedSource, aquiferViz);
When a different layer is selected, a function is triggered like so:
function setIntergranular() {
aquiferLayer.update(intergranularSource, aquiferViz);
}
The layer updates as intended, but the legend remains the same. Is it possible for the legend to update as well? For extra reference, my legend is added using the following code:
// A function to convert map colors to HEX values for legend
function rgbToHex(color) {
return "#" + ((1 << 24) + (color.r << 16) + (color.g << 8) + color.b).toString(16).slice(1);
}
// When layer loads, trigger legend event
aquiferLayer.on('loaded', () => {
// Request data for legend from the layer viz
const colorLegend = aquiferLayer.viz.color.getLegendData();
let colorLegendList = '';
// Create list elements for legend
colorLegend.data.forEach((legend, index) => {
const color = rgbToHex(legend.value);
// Style for legend items
colorLegendList +=
`<li><span class="point-mark" style="background-color:${color};border: 1px solid black;"></span> <span>${legend.key}</span></li>\n`;
});
// Place list items in the content section of the title/legend box
document.getElementById('contentLegend').innerHTML = colorLegendList;
});