Can I access the data portion of the SQL queries used in the cartodb.createLayer function without the use of special event handlers?

I am making a choropleth map, and categorizing the data with Jenks natural breaks. So, in order to determine the breaks needed to set the right values in CartoCSS, I need to access all values in the data, run the Jenks process, and set the proper CartoCSS. Currently I do this via an independent SQL query prior to running createLayer:

var sql = new cartodb.SQL({ user: 'user' });
var sqlQuery = "SELECT * FROM table;"

This works fine, but I would rather not run the independent SQL query, if I can somehow extract that information from the createLayer function.

I set up the layer source with four sublayers:

var layerSource = {
  user_name: 'user',
  type: 'cartodb',
  sublayers: [
      sql: q1,
      interactivity: 'cartodb_id',
      cartocss: s1
      sql: q2,
      interactivity: 'cartodb_id',
      cartocss: s2

      sql: q3,
      interactivity: 'cartodb_id',
      cartocss: s3

      sql: q4,
      interactivity: 'cartodb_id',
      cartocss: s4

Then I create the layers:

cartodb.createLayer(map, layerSource, {cartodb_logo: false})
.done(function(layer) {
  for (var i = 0; i < layer.getSubLayerCount(); i++) {
    subLayers[i] = layer.getSubLayer(i);


I know of no way to extract the attribute values from the four SQL queries that are called to the make the layer - from neither the returned 'layer' nor any of the elements in subLayers.

I can access the 'data' from a featureOver or featureClick event handler on a sublayer, e.g.

 subLayer[0].on('featureOver', function(e,pos,latlng,data){
    if (data.cartodb_id != highlight.cartodb_id) {

but I need the data before that - to set up CartoCSS and create a proper legend.

Any ideas?

1 Answer 1


The vizjson file that defines the layer doesn't contain the data you need. Take a look at the response of the request triggered by createLayer, which looks like http://documentation.cartodb.com/api/v2/viz/2b13c956-e7c1-11e2-806b-5404a6a683d5/viz.json?callback=vizjson (too long to be pasted here).

Maps API is focused on presentation and SQL API is focused in data, so requesting it with the SQL API is definitely the way to go.

  • Generally speaking, We're looking for long answers that provide some explanation and context. Please don't give a one-line answer; explain why your answer is right, ideally with citations. Commented Mar 25, 2015 at 8:45
  • 1
    Ok, improved with some information, hope it's more helpful now. Commented Mar 25, 2015 at 12:53

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.