3

I know that I can generate a choropleth using CartoCSS like this:

#volume [ number_of_cases <= 434] {
   marker-fill: #BD0026;
}
#volume [ number_of_cases <= 183] {
   marker-fill: #F03B20;
}
#volume [ number_of_cases <= 130] {
   marker-fill: #FD8D3C;
}
#volume [ number_of_cases <= 90] {
   marker-fill: #FECC5C;
}
#volume [ number_of_cases <= 50] {
   marker-fill: #FFFFB2;
}

That works fine. However, I'm changing the field that sets the volume dynamically. For example, it might be the number of "widgets" and then it might be the number of "thingies". What I can't have is these ranges in the CartoCSS set the same for each product (widgets and thingies). The ranges need to be set "on the fly" based on the possible ranges in the number_of_cases column, as they have very different ranges. What I need is something that generates the ranges similar to how the CartoDB editor works, but to do it all dynamically.

3

Assuming you are using cartodb.js and building a custom site, you would need to use the SQL api to get the range of data, then build out your cartoCSS using javascript, then use the sublayer.setCartoCSS() method to style your map on the fly.

Some pseudocode:

$.getJSON('https://{account}.cartodb.com/api/v2/sql?q=SELECT MAX(column), MIN(column) FROM myTable&api_key={Your API key}',function(response){
  var range=max-min;
  var colors = [color1,color2,color3,color4,color5];

  //get the incremental value for each step based on the range
  var step = range/colors.length;

  colors.forEach(function(color,i){
    var value = min + (step * i);
    var color = colors[i];
    //build a cartoCSS Rule as a string using these values
    thisCartoCSS = '#tablename [value<=' + value + '] {marker-fill:' + color + '};';
    allCartoCSS += thisCartoCSS;
    //when you're done building all of the cartoCSS, use sublayer.setCartoCSS() to apply it to your layer
  })

});

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.