I have made a map that shows fire risk for the different Districts within South Africa, and each fire risk is styled by value to match a certain color. I am trying to add a legend to show what each colour relates to a field (extreme, high, medium or low-risk level) but I am not having any luck. There is this legend example on the CARTO docs, but it is a little tricky to adapt to my code.

I have added the code and a CodePen, and here are the layer properties:

enter image description here

overall is the column I would like to represent in the legend.

2 Answers 2


You were almost there. I've created a diff to show you the places where you need to make some adjustments. Code diff with the explanation

  1. You didn't have the style for painting the circles. Added to the CSS.
  2. Your cartoCSS asked for a ramp on polygon-fill but you were then asking for marker-fill metadata, I guess based on our examples that are based on point instead of polygons.
  3. While traversing the categories, you need to go through the category name.

There you have a clone of you codepen working


  • Brilliant, thanks Ivan! I really appreciate the extra info to show me where I was going wrong, I just learnt so much. Cheers
    – JohnGIS
    Jul 11, 2018 at 10:59

You should get the building blocks from the docs example. First of all, you need to add a legend container:

<!-- legend -->
<div id="legend">
  <div id="legend-content">

Then after adding your basemap and layer, you should add a js script similar to this one:

const legend = $("#legend-content");

layer.on('metadataChanged', renderCategoryLegend);

function renderCategoryLegend(metadata){
  metadata.styles.forEach(function (styleMetadata) {
    if (styleMetadata.getProperty() == 'marker-fill') {
        let categories = styleMetadata.getCategories();
        for (category of categories){
          legend.append(`<li><div class="circle" style="background:${category.value}"></div> ${category.name}</li>`)

First, get the legend container. Secondly, assign a function that renders the legend when the metadata changes. Third, this function gets the metadata information, get the categories from the marker-fill ramp and append an element with the name and color.

Here is the whole code.

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.