1

I have made a CARTO VL map that allows the user to update the active layer depending on which groundwater aquifer option is selected.

enter image description here

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;
});

2 Answers 2

4

Exactly! The 'loaded' event is only fired when the layer is loaded, but the 'updated' event is fired every time the layer is updated. You can take a look at this example: https://carto.com/developers/carto-vl/examples/#example-viewport-summary

We recommend using the 'updated' event only if you need the widget information to change, but if it's going to remain static, it's better to use 'loaded'.

1

The solution is to change the trigger legend event from 'loaded' to 'updated':

aquiferLayer.on('updated', () => {})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.