block by andrewxhill 7b6be7f87d1af6ac53a3

Static Image Generator Example

Full Screen

A basic class that allows you to quickly generate static images from the CartoDB API using custom CartoCSS builders etc.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>L</title>
  <meta name=viewport content="width=device-width initial-scale=1">
  <script src="//libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
  <link href="//cartodb.com/favicon.ico" rel="shortcut icon" />
  <style type="text/css">
    html,
    body {
      position: relative;
      height: 100%;
      padding: 0;
      margin: 0;
    }
  </style>
</head>

<body>

  <div class="preview" id="preview"></div>

  <script>
    var CartoImage = function(width, height, account, table, column, zoom, lat, lon, colors){
      this.width = width;
      this.height = height;
      this.account = account;
      this.table = table;
      this.column = column;
      this.colors = colors;
      this.zoom = zoom;
      this.center_lat = lat;
      this.center_lon = lon;
      this.sql = cartodb.SQL({ user: this.account })
    }
    CartoImage.prototype.getHeight = function() { return this.height };
    CartoImage.prototype.getWidth = function() { return this.width };
    CartoImage.prototype.setURL = function(layergroup) {
          var path = [
              cartoimage.getEndpoint(),
              'static',
              'center',
              layergroup.layergroupid,
              this.zoom, this.center_lat, this.center_lon,
              cartoimage.getWidth(),
              cartoimage.getHeight()
          ].join('/');
          this.url = path + '.png';
          this.callback(this.url)
    };
    CartoImage.prototype.getEndpoint = function() { return 'https://'+this.account+'.cartodb.com/api/v1/map' };

    CartoImage.prototype.createConfig = function (values) {
      console.log(values)
      var config = this.getConfig(values.jenks)
      var jsonMapConfig = JSON.stringify(config, null, 2);
      var request = new XMLHttpRequest();
      request.open('POST', this.getEndpoint(), true);
      request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
      request.onload = this.imgFromLayerGroup;
      request.send(jsonMapConfig);
    }

    CartoImage.prototype.init = function(callback){
      this.callback = callback;
      this.sql.describeFloat('select * from '+this.table, this.column, this.createConfig.bind(this))
    }
    CartoImage.prototype.imgFromLayerGroup = function(){
        if (this.status >= 200 && this.status < 400) {
            var layergroup = JSON.parse(this.response);
            console.log(layergroup);
            cartoimage.setURL(layergroup);
        } else {
            throw 'Error calling server: Error ' + this.status + ' -> ' + this.response;
        }
    }

    CartoImage.prototype.getConfig = function(ramp){

      var cartocss = "#layer {\n\tpolygon-fill: "+this.colors[0]+";\n\tpolygon-opacity: 0.5;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0; ";
      var c = 0;
      for (i in ramp){
        cartocss += "["+this.column+" <= "+i+"]{polygon-fill: "+this.colors[c]+";}"
        c+=1
      }
      cartocss += " \n}"
      var config = {
          "version": "1.3.0",
          "layers": [
            {
              "type": "http",
              "options": {
                "urlTemplate": "//{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png",
                "subdomains": [
                  "a",
                  "b",
                  "c"
                ]
              }
            },
            {
              "type": "mapnik",
              "options": {
                "sql": "select * from "+this.table,
                "cartocss": cartocss,
                "cartocss_version": "2.2.0"
              }
            }
          ]
        }
        return config;
    }

    var colors = [ '#65B1D0', '#3AB9B6', '#4EBB90', '#7CB768', '#AAAF4C', '#D3A149', '#F29160' ];
    // setup your new Image with some default parameters
    var cartoimage = new CartoImage(500, 200, 'observatory', 'us_census_acs2013_5yr_block_group', 'median_rent_moe', 3, 40, -100, colors);

    window.onload = function() {
      var myCustomImageHandlingFunction = function(url){
        // will get back the URL of your desired image
        var ig = new Image();
        ig.src = url;
        $('body').append(ig);
        console.log(url)
      }
      cartoimage.init(myCustomImageHandlingFunction)
    }

  </script>
</body>

</html>