Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewxhill committed Feb 13, 2012
0 parents commit e02f7af
Show file tree
Hide file tree
Showing 11 changed files with 2,471 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
@@ -0,0 +1,18 @@
CartoD3
================

a library for creating D3 graphs from a Backbone.CartoDB model object

usage
-----



examples
--------






210 changes: 210 additions & 0 deletions examples/backbone.cartodb.js
@@ -0,0 +1,210 @@

/**
*
* backbone cartodb adapter
*
* this is a small library that allows to use Backbone with models
* to work with data stored in CartoDB (a geospatial database on
* the cloud, see more info at http://cartodb.com).
*
* it does NOT overrride Backbone.sync
*
*/

Backbone.CartoDB = function(options, query, cache) {

options = _.defaults(options, {
USE_PROXY: false,
user: ''
});

function _SQL(sql) {
this.sql = sql;
}
function SQL(sql) {
return new _SQL(sql);
}

// SQL("{0} is {1}").format("CartoDB", "epic!");
_SQL.prototype.format = function() {
var str = this.sql,
len = arguments.length+1;
var safe, arg;
for (i=0; i < len; arg = arguments[i++]) {
safe = typeof arg === 'object' ? JSON.stringify(arg) : arg;
str = str.replace(RegExp('\\{'+(i-1)+'\\}', 'g'), safe);
}
return str;
};


var resource_path= options.user + '.cartodb.com/api/v1/sql';
var resource_url = 'https://' + resource_path;

/**
* fetch sql from the server
*
* this function should be changed if you're working on node
*
*/
query = query || function(sql, callback, proxy) {
var url = resource_url;
var crossDomain = true;
if(proxy) {
url = 'api/v0/proxy/' + resource_url;
crossDomain = false;
}
if(sql.length > 1500) {
$.ajax({
url: url,
crossDomain: crossDomain,
type: 'POST',
dataType: 'json',
data: 'q=' + encodeURIComponent(sql),
success: callback,
error: function(){
if(proxy) {
callback();
} else {
//try fallback
if(USE_PROXY) {
query(sql, callback, true);
}
}
}
});
} else {
// TODO: add timeout
$.getJSON(resource_url + '?q=' + encodeURIComponent(sql) + '&callback=?')
.success(callback)
.fail(function(){
callback();
}).complete(function() {
});
}
};

var dummy_cache = {
setItem: function(key, value) { },
getItem: function(key) { return null; },
removeItem: function(key) { }
};

cache = cache && dummy_cache;


var CartoDBModel = Backbone.Model.extend({

_create_sql: function() {
var where = SQL(" where {0} = '{1}'").format(
this.columns[this.what],
this.get(this.what).replace("'", "''")
);
var select = this._sql_select();
var sql = 'select ' + select.join(',') + ' from ' + this.table + where;
return sql;
},

_sql_select: function() {
var select = [];
for(var k in this.columns) {
var w = this.columns[k];
if(w.indexOf('ST_') !== -1 || w === "the_geom") {
select.push(SQL('ST_AsGeoJSON({1}) as {0}').format(k,w));
} else {
select.push(SQL('{1} as {0}').format(k, w));
}
}
return select;
},

_parse_columns: function(row) {
var parsed = {};
for(var k in row) {
var v = row[k];
var c = this.columns[k];
if (c.indexOf('ST_') !== -1 || c === "the_geom") {
parsed[k] = JSON.parse(v);
} else {
parsed[k] = row[k];
}
}
return parsed;
},

fetch: function() {
var self = this;
query(this._create_sql(), function(data) {
self.set(self._parse_columns(data.rows[0]));
});
}
});


/**
* cartodb collection created from a sql composed using 'columns' and
* 'table' attributes defined in a child class
*
* var C = CartoDBCollection.extend({
* table: 'table',
* columns: ['c1', 'c2']
* });
* var c = new C();
* c.fetch();
*/
var CartoDBCollection = Backbone.Collection.extend({

_create_sql: function() {
var tables = this.table;
if(!_.isArray(this.table)) {
tables = [this.table];
}
tables = tables.join(',');
var select = CartoDBModel.prototype._sql_select.call(this);
var sql = 'select ' + select.join(',') + ' from ' + this.table;
if (this.where) {
sql += " WHERE " + this.where;
}
return sql;
},

fetch: function() {
var self = this;
var sql = this.sql || this._create_sql();
if(typeof(sql) === "function") {
sql = sql.call(this);
}
var item = this.cache ? cache.getItem(sql): false;
if(!item) {
query(sql, function(data) {
if(this.cache) {
try {
cache.setItem(sql, JSON.stringify(data.rows));
} catch(e) {}
}
var rows;
if(!self.sql) {
rows = _.map(data.rows, function(r) {
return CartoDBModel.prototype._parse_columns.call(self, r);
});
} else {
rows = data.rows;
}
self.reset(rows);
});
} else {
self.reset(JSON.parse(item));
}
}

});


return {
query: query,
CartoDBCollection: CartoDBCollection,
CartoDBModel: CartoDBModel,
SQL: SQL
};

};
44 changes: 44 additions & 0 deletions examples/barchart.html
@@ -0,0 +1,44 @@
<!--
You are free to copy and use this sample in accordance with the terms of the
Apache license (http://www.apache.org/licenses/LICENSE-2.0.html)
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>D3 Visualization API Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="libs/underscore-1.1.6.js"></script>
<script type="text/javascript" src="libs/backbone.js"></script>
<script type="text/javascript" src="libs/d3.min.js"></script>
<script type="text/javascript" src="backbone.cartodb.js"></script>
<script type="text/javascript" src="d3.cartodb.js"></script>
<link href='css/cartodb.d3.default.css' rel='stylesheet' type='text/css' />
<style type="text/css">
#cartodb_d3 {
float: left; width: 800px;
}
</style>
<script type="text/javascript">
var CartoDB = Backbone.CartoDB({
user: 'examples', // you should put your account name here
table: 'earthquakes' // you should put your account name here
});
var EarthQuakes = CartoDB.CartoDBCollection.extend({
sql: function() {
return "select month,avg(magnitude) as magnitude from earthquakes group by month order by month asc";
}
});
var eq = new EarthQuakes();

var CartoD3 = Backbone.CartoD3(eq);
$(document).ready(function() {
var barchart = new CartoD3.Barchart({ container: "cartodb_d3", variable: 'magnitude', label: 'month'});
});
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="cartodb_d3"></div>
</body>
</html>
45 changes: 45 additions & 0 deletions examples/bubble.html
@@ -0,0 +1,45 @@
<!--
You are free to copy and use this sample in accordance with the terms of the
Apache license (http://www.apache.org/licenses/LICENSE-2.0.html)
-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>D3 Visualization API Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="libs/underscore-1.1.6.js"></script>
<script type="text/javascript" src="libs/backbone.js"></script>
<script type="text/javascript" src="libs/d3.min.js?v=2.7.4"></script>
<script type="text/javascript" src="libs/d3.layout.min.js?v=2.7.4"></script>
<script type="text/javascript" src="backbone.cartodb.js"></script>
<script type="text/javascript" src="d3.cartodb.js"></script>
<link href='css/cartodb.d3.default.css' rel='stylesheet' type='text/css' />
<style type="text/css">
#cartodb_d3 {
float: left; width: 800px;
}
</style>
<script type="text/javascript">
var CartoDB = Backbone.CartoDB({
user: 'examples', // you should put your account name here
table: 'earthquakes' // you should put your account name here
});
var EarthQuakes = CartoDB.CartoDBCollection.extend({
sql: function() {
return "SELECT iso_a3,floor(gdp_md_est / 1000) as gdp_md_est, floor(pop_est / 1000000) as pop_est FROM country_population";
}
});
var eq = new EarthQuakes();

var CartoD3 = Backbone.CartoD3(eq);
$(document).ready(function() {
var bubble = new CartoD3.BubbleSVG({ container: "cartodb_d3", variable: 'pop_est', label: 'iso_a3', fill: 'gdp_md_est'});
});
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="cartodb_d3"></div>
</body>
</html>
19 changes: 19 additions & 0 deletions examples/css/cartodb.d3.default.css
@@ -0,0 +1,19 @@

.CartoDB_D3.Barchart div {
font: 10px sans-serif;
min-height: 5px;
background-color: steelblue;
text-align: right;
padding: 3px;
margin: 1px;
color: white;
}

.CartoDB_D3.Bubble circle {
stroke: #fff;
stroke-width: 1.5px;
}

.CartoDB_D3.Bubble text {
font: 6px sans-serif;
}

0 comments on commit e02f7af

Please sign in to comment.