0

I am trying to construct a legend based on size using Carto VL, and am struggling to implement the solution posed in this Github thread.

https://github.com/CartoDB/carto-vl/issues/1260

I built a box to house the legend earlier in the code, here is the code I have so far that constructs the legend itself. What is this code missing?

const Legend = piceaLayer.viz.width.getLegendData(
                  width : ramp(($picea), [1, 2, 3]);
                 [{key: '10%', value: 10,
                   key: '50%', value: 50,
                   key: '100%', value: 100}]


               document.getElementById('legend').innerHTML = LegendList;

0

You are mixing the viz declaration with the getLegendData method to retrieve the metadata of your visualization.

So first declare your width property:

const viz = new carto.Viz(`
        width: ramp($total_damage, [5, 25, 50])
        color: opacity(white, 0.5)
        strokeWidth: 0
    `);

And then retrieve your legend data elsewhere:

layer.on('loaded', () => {

            // Request data for legend from the layer viz
            const widthLegend = layer.viz.width.getLegendData({
            });

            let widthLegendList = '';

            // Create list elements for legend
            widthLegend.data.forEach((legend, index) => {

                widthLegendList +=
                    `<li><div class="circle" style="background: #DCDCDC; width:${legend.value}px; height:${legend.value}px;"></div> ${legend.key.toFixed(0)}</li>`;
            });

            // Place list items in the content section of the title/legend box
            document.getElementById('content').innerHTML = widthLegendList;

        });

The result is not very elegant but it works. You can see the full code here.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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