0

Does anyone know how to add labels (using a feature column such as "state") to a CARTO.js layer? This is how I have added the layer to my map:

const boundariesDataset = new carto.source.Dataset(`
      districtmunicipality2016
    `);
    const boundariesStyle = new carto.style.CartoCSS(`
      #layer {        
        ::outline {
          line-width: 1;
          line-color: #000000;
          line-opacity: 1;
        }
      }
    `);
    const boundaries = new carto.layer.Layer(boundariesDataset, boundariesStyle, {
        featureOverColumns: ['district_n']
    });

Ps, this line:

featureOverColumns: ['district_n']

Is used to select a feature to display in a pop up, using:

const popup = L.popup({ closeButton: false });
        boundaries.on(carto.layer.events.FEATURE_OVER, featureEvent => {
          popup.setLatLng(featureEvent.latLng);
          if (!popup.isOpen()) {
            popup.setContent(featureEvent.data.district_n);
            popup.openOn(map);
          }
        });
3

You can add labels in CARTO.js using CartoCSS text properties in your layer style object. Something like this should work:

#layer {
  polygon-fill: #826DBA;
  polygon-opacity: 0.9;
}
#layer::outline {
  line-width: 1;
  line-color: #FFFFFF;
  line-opacity: 0.5;
}
#layer::labels {
  text-name: [name];
  text-face-name: 'DejaVu Sans Book';
  text-size: 10;
  text-fill: #FFFFFF;
  text-label-position-tolerance: 0;
  text-halo-radius: 1;
  text-halo-fill: #6F808D;
  text-dy: -10;
  text-allow-overlap: true;
  text-placement: point;
  text-placement-type: dummy;
}

You would need to replace the name field with your proper column name.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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