1

I've got a working example of a map that adds a marker layer with the creatLayer method. I am trying to add a click listener to the carto markers. I have tried the examples here and here to no avail.

Here is where I am at right now. You'll see the markers are loading, but no interaction on click (it should call an alert). I have tried a lot of variations on the click listener code at this point.

Code pasted below as well.

<!DOCTYPE html>
<html>
<head>
<title>How to add markers to a CARTO map</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<style>
  html, body, #map {
    height: 100%;
    padding: 0;
    margin: 0;
  }  
</style>
<!-- include cartodb.js CSS library -->
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
 <!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
</head>
<body>

<div id="map"></div>

<script>
  function main() {
    var map = new L.Map('map', {
      center: [40.7328,-74.0059],
      zoom: 14
    });
    // var layer = L.mapbox.styleLayer('mapbox://styles/fluffywolf24/cimhxr71f0021qxno7nts1d4w', { detectRetina: true });
    // layer.addTo(map);
    // console.log('map:', map);
    L.tileLayer('http://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {attribution: 'OpenStreetMaps'
    }).addTo(map);
    cartodb.createLayer(map, {
      user_name: 'whayler1',
      type: 'cartodb',
      sublayers: [{
        sql: "SELECT * FROM ny_listings",
        cartocss: '#layer{marker-fill-opacity: 0.7; marker-line-color: #B40903; marker-line-width: 1; marker-line-opacity: 0; marker-placement: point; marker-type: ellipse; marker-width: 1; marker-fill: #F11810; marker-allow-overlap: true; } #layer::point{marker-fill-opacity: 0.4; marker-line-color: #B40903; marker-line-width: 1; marker-line-opacity: 1; marker-placement: point; marker-type: ellipse; marker-width: 7; marker-fill: #F11810; marker-allow-overlap: true; }'}]
    })
    .addTo(map)
    .done(function(layer) {
      console.log('done', layer);
      layer.setInteraction(true);
      layer.on('featureClick', function(e, latlon, pos, data, subLayerIndex) {
        alert("clicked marker!");
        console.log(data);
      });
    });
  }
  window.onload = main;
</script>
</body>
</html> 
1

Add an interactivity line to your sublayer definition that exposes at least one column from your dataset:

sublayers: [{
        sql: 'SELECT * FROM ny_listings',
        cartocss: '...',
        interactivity: "cartodb_id,address"
      }]

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.