Skip to content

Instantly share code, notes, and snippets.

@almccon
Forked from rochoa/README.md
Last active June 15, 2016 20:15
Show Gist options
  • Save almccon/7dccb3776b877fec6ae5c275323588b6 to your computer and use it in GitHub Desktop.
Save almccon/7dccb3776b877fec6ae5c275323588b6 to your computer and use it in GitHub Desktop.
turbo-cartocss examples

Color ramps: *-fill

Basic usage

marker-fill: ramp([column_name], colorbrewer(Greens));
                  |                    |
                  v                    |
      column to calculate ramp         |
                                       v
                it will use a color ramp from http://colorbrewer2.org/

Change number of color brewer data classes

marker-fill: ramp([column_name], colorbrewer(YlGnBu, 7));
                                                     |
                                                     v
                                          force number of classes
                                            default: 5 classes

Change quantification method

marker-fill: ramp([column_name], colorbrewer(Reds), jenks);
                                                      |
                                                      v
                                         force quantification method
                                             default: quantiles

Numeric ramps: *-width, *-opacity

Basic usage

marker-width: ramp([column_name], 4, 18);
                   |              |   |
                   v              |   |
       column to calculate ramp   |   |
                                  v   |
           start value for the ramp   |
                                      |
                                      v
                            end value for the ramp

Change quantification method

marker-width: ramp([column_name], 4, 18, equal);
                                           |
                                           v
                               force quantification method
                                    default: quantiles

Change number of buckets

marker-width: ramp([column_name], 4, 18, 6);
                                         |
                                         v
                              force number of buckets
                                    default: 5

Change both: number of buckets and quantification method

marker-width: ramp([column_name], 4, 18, 6, jenks);
                                         |    |
                                         v    |
                   force number of classes    |
                                              v
                                 force quantification method

Options

Quantification methods

var map = L.map('map', {
scrollWheelZoom: false,
center: [-18, -46],
zoom: 8
});
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '<a href="http://cartodb.com">CartoDB</a> © 2014',
maxZoom: 18
}).addTo(map);
var sqlEditor = CodeMirror.fromTextArea(document.getElementById('sql_editor'), {
theme: 'monokai',
lineNumbers: true,
lineWrapping: true,
mode: "text/x-plsql",
height: "100px"
});
var cssEditor = CodeMirror.fromTextArea(document.getElementById('css_editor'), {
theme: 'monokai',
lineNumbers: true,
mode: "text/x-scss",
height: "200px"
});
var tilesLayer = null;
function updateMap(example) {
if (tilesLayer) {
map.removeLayer(tilesLayer);
}
if (example) {
map.setView(example.center, example.zoom);
}
var config = {
"version": "1.2.0",
"layers": [
{
"type": "cartodb",
"options": {
"sql": sqlEditor.getValue(),
"cartocss": cssEditor.getValue(),
"cartocss_version": "2.3.0"
}
}
]
};
var request = new XMLHttpRequest();
request.open('POST', currentEndpoint(), true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.onload = function() {
if (this.status >= 200 && this.status < 400){
var layergroup = JSON.parse(this.response);
var tilesEndpoint = currentEndpoint() + '/' + layergroup.layergroupid + '/{z}/{x}/{y}.png';
var protocol = 'https:' == document.location.protocol ? 'https' : 'http';
if (layergroup.cdn_url && layergroup.cdn_url[protocol]) {
var domain = layergroup.cdn_url[protocol];
if ('http' === protocol) {
domain = '{s}.' + domain;
}
tilesEndpoint = protocol + '://' + domain + '/' + currentUser() + '/api/v1/map/' + layergroup.layergroupid + '/{z}/{x}/{y}.png';
}
tilesLayer = L.tileLayer(tilesEndpoint, {
maxZoom: 18
}).addTo(map);
} else {
throw 'Error calling server: Error ' + this.status + ' -> ' + this.response;
}
};
request.send(JSON.stringify(config));
}
function currentExample() {
return examples[examplesSelector.value];
}
function currentUser() {
return currentEndpoint().match(/http[s]*:\/\/([^.]*).*/)[1];
}
function currentEndpoint() {
return document.getElementById('endpoint').value;
}
function loadExample() {
var example = currentExample();
cssEditor.setValue(example.cartocss);
sqlEditor.setValue(example.sql);
updateMap(example);
}
CodeMirror.commands.save = function() {
updateMap();
};
var examplesSelector = document.getElementById('examples');
examplesSelector.addEventListener('change', loadExample, false);
Object.keys(examples).forEach(function(k) {
var option = document.createElement('option');
option.value = k;
option.innerText = k;
examplesSelector.appendChild(option);
});
document.getElementById('endpoint').addEventListener('blur', function() {
updateMap();
}, false);
loadExample();
function getCartoCss(id, rules) {
return '#' + id + ' {\n\t' +
rules.join('\n\t')
+ '\n}'
}
var DEFAULT_STYLE = [
"#points['mapnik::geometry_type'=1] {",
" marker-fill-opacity: 0.7;",
" marker-line-color: #FFF;",
" marker-line-width: 0.5;",
" marker-line-opacity: 1;",
" marker-placement: point;",
" marker-type: ellipse;",
" marker-width: 4;",
" marker-fill: red;",
" marker-allow-overlap: true;",
"}",
"#lines['mapnik::geometry_type'=2] {",
" line-color: red;",
" line-width: 2;",
" line-opacity: 1.0;",
"}",
"#polygons['mapnik::geometry_type'=3] {",
" polygon-fill: red;",
" polygon-opacity: 0.7;",
" line-color: #FFF;",
" line-width: 0.5;",
" line-opacity: 1;",
"}"
].join('\n');
// All of these could be standardized to use 7 colors
// EGBERT / 117181
var colors_1 = [
'#9bbbd5',
'#8cacc6',
'#7d9cb6',
'#6e8da7',
'#5e7e98',
'#4f6f88',
'#406079',
'#315069',
'#22415a'
];
// OLIVE / 117185
var colors_2 = [
'#b5c88d',
'#9cb075',
'#84975d',
'#6b7f44',
'#53662c',
'#3a4e14'
];
// RAPUNZEL / 117186
var colors_3 = [
'#f4bb84',
'#e3aa74',
'#d19865',
'#c08755',
'#ae7646',
'#9d6536',
'#8b5327',
'#7a4217'
];
// HELEN / 130828
var colors_4 = [
'#94c7b6',
'#77a997',
'#5b8a79',
'#3e6b5a',
'#214d3b'
];
// SCOOTER / 130830
var colors_5 = [
'#e38f8f',
'#c57372',
'#a75655',
'#893a38',
'#6b1d1b'
];
// WALTER / 130832
var colors_6 = [
'#e49bc1',
'#c67ea3',
'#a86184',
'#894466',
'#6b2747'
];
// UNNAMED / 139413
var colors_7 = [
'#c2a8cc',
'#482e51'
];
var examples = {
'ospreys-manual': {
sql: [
"SELECT id, year, season,",
"(year::text || '-' || season) as cartodb_id,",
"CASE WHEN season = 'spring' THEN year*10 + 1 ELSE year+10 + 2 END AS year_and_season,",
" ST_MakeLine(",
" ST_Transform(",
" ST_SetSRID(",
" ST_MakePoint(lon, lat),",
" 4326),",
" 3857)",
" ORDER BY timestamp DESC",
" ) as the_geom_webmercator",
"FROM",
"(",
" SELECT *, ",
" ST_Distance(",
" the_geom_webmercator, ",
" lag(the_geom_webmercator) ",
" OVER (",
" ORDER BY id, timestamp",
" )",
" ) AS dist ",
" FROM",
" movebank_api_output",
") as _",
"WHERE season != 'other'",
"AND dist < 100000",
"GROUP BY id, year, season",
"order by cartodb_id",
].join('\n'),
cartocss: [
"#layer{",
" line-width: 3;",
" line-opacity: 0.8;",
" line-join: round;",
" [id=117181]{ line-color: ramp([year_and_season],(" + colors_1.join() + ")); } /* Egbert */",
" [id=117185]{ line-color: ramp([year_and_season],(" + colors_2.join() + ")); } /* Olive */",
" [id=117186]{ line-color: ramp([year_and_season],(" + colors_3.join() + ")); } /* Rapunzel */",
" [id=130828]{ line-color: ramp([year_and_season],(" + colors_4.join() + ")); } /* Helen */",
" [id=130830]{ line-color: ramp([year_and_season],(" + colors_5.join() + ")); } /* Scooter */",
" [id=130832]{ line-color: ramp([year_and_season],(" + colors_6.join() + ")); } /* Walter */",
" [id=139413]{ line-color: ramp([year_and_season],(" + colors_7.join() + ")); } /* Unnamed */",
"}"
].join('\n'),
center: [45, -110],
zoom: 5
},
'ospreys-colorbrewer': {
sql: [
"SELECT id, year, season,",
"(year::text || '-' || season) as cartodb_id,",
"CASE WHEN season = 'spring' THEN year*10 + 1 ELSE year+10 + 2 END AS year_and_season,",
" ST_MakeLine(",
" ST_Transform(",
" ST_SetSRID(",
" ST_MakePoint(lon, lat),",
" 4326),",
" 3857)",
" ORDER BY timestamp DESC",
" ) as the_geom_webmercator",
"FROM",
"(",
" SELECT *, ",
" ST_Distance(",
" the_geom_webmercator, ",
" lag(the_geom_webmercator) ",
" OVER (",
" ORDER BY id, timestamp",
" )",
" ) AS dist ",
" FROM",
" movebank_api_output",
") as _",
"WHERE season != 'other'",
"AND dist < 100000",
"GROUP BY id, year, season",
"order by cartodb_id",
].join('\n'),
cartocss: [
"#layer{",
" line-width: 3;",
" line-opacity: 0.8;",
" line-join: round;",
" [id=117181]{ line-color: ramp([year_and_season],colorbrewer(Blues)); } /* Egbert */",
" [id=117185]{ line-color: ramp([year_and_season],colorbrewer(Greens)); } /* Olive */",
" [id=117186]{ line-color: ramp([year_and_season],colorbrewer(YlOrBr)); } /* Rapunzel */",
" [id=130828]{ line-color: ramp([year_and_season],colorbrewer(BuGr)); } /* Helen */",
" [id=130830]{ line-color: ramp([year_and_season],colorbrewer(Oranges)); } /* Scooter */",
" [id=130832]{ line-color: ramp([year_and_season],colorbrewer(PuRd)); } /* Walter */",
" [id=139413]{ line-color: ramp([year_and_season],colorbrewer(Purples)); } /* Unnamed */",
"}"
].join('\n'),
center: [45, -110],
zoom: 5
}
};
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css" />
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/4.7.0/codemirror.min.css">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/codemirror/4.7.0/theme/monokai.min.css">
<style>
body {
margin: 16px;
padding: 0;
border: 0;
font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif;
}
textarea {
padding: 0;
margin: 0;
border: solid 1px #999;
height: 64px;
}
.wrap {
width: 960px;
margin: 0 auto;
}
.loader, .editor, .options {
border-bottom: solid 1px #666;
padding: 16px 0;
}
.loader input, .loader select {
margin: 0 24px;
}
.loader input {
width: 320px;
}
.editor label {
width: 480px;
margin-bottom: 12px;
display: block;
float: left;
}
.CodeMirror {
float: left;
width: 479px;
border-left: 1px solid #fff;
height: 160px;
}
#map {
clear: both;
width: 960px;
height: 480px;
margin-top: 16px;
}
.clear {
clear: both;
}
</style>
</head>
<body>
<div class="wrap">
<form class="loader">
<label for="examples">Examples</label>
<select name="examples" id="examples"></select>
<label for="endpoint">Maps API endpoint</label>
<input type="text" name="endpoint" id="endpoint" value="https://mpgranch.cartodb.com/api/v1/map">
</form>
<!-- <form class="options">
<input type="checkbox" name="raster" id="raster"> <label for="raster">Raster</label>
</form> -->
<form class="editor">
<label for="sql_editor">SQL</label>
<label for="css_editor">CartoCSS</label>
<textarea id="sql_editor" class="code"></textarea>
<textarea id="css_editor" class="code"></textarea>
<div class="clear"></div>
</form>
<div id="map"></div>
</div>
</body>
<script src="//cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/4.7.0/codemirror.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/4.7.0/mode/css/css.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/codemirror/4.7.0/mode/sql/sql.min.js"></script>
<script src="examples.js"></script>
<script src="app.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment