How do I centre my map after clicking on a marker in carto js? I'm using createLayer but not sure where my listener should be applied (i.e. to map object created using Leaflet or within createLayer call).

  • The listener should be applied to the featureclick within the createLayer done call, and use the Leaflet center map functionality.
    – Jags
    Oct 6, 2017 at 6:51

1 Answer 1


As @Jags have commented, you have to apply a featureclick to the listener and then you can use getBounds method to get the bbox (or marker position) from the selected feature and finally set the view and zoom according to the output parameters:

sublayer.on('featureClick', function(e, pos, latlng, data) {

  // get cartodb_id from selected feature
  var id_selected = data.cartodb_id;

  // get bounds from selected feature
  var sql = new cartodb.SQL({ user: 'ramirocartodb'});
    query + " where cartodb_id = {{cartodb_id}}", 
    {cartodb_id: id_selected})
  .done(function(bounds) {

    // zoom to selected feature
    let newLat = (bounds[0][0]+bounds[1][0])*0.50, newLong = (bounds[0][1]+bounds[1][1])*0.50;
    map.setView([newLat, newLong],10,true);

Here you have a working example.

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.