Skip to content

Instantly share code, notes, and snippets.

@auremoser
Last active October 12, 2017 03:49
Show Gist options
  • Save auremoser/96b70f6dbcc724ecc973 to your computer and use it in GitHub Desktop.
Save auremoser/96b70f6dbcc724ecc973 to your computer and use it in GitHub Desktop.
Beirut Workshop II: Map + Chart
<!DOCTYPE html>
<html>
<title>Blackout Map</title>
<link rel="shortcut icon" href="https://raw.githubusercontent.com/auremoser/images/master/lightning-favicon.ico" type="image/x-icon">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<!-- add cartoCSS stylesheet -->
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/themes/css/cartodb.css"/>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#header {
background-color: #fff;
color: #252525;
font-family: 'Unica One', sans-serif;
font-size: 54px;
padding: 0;
text-align: center;
text-transform: uppercase;
}
#map {
bottom: 0;
left: 0;
position: absolute;
right: 0;
top: 70px;
}
#temp {
bottom: 0;
display:none;
height: 300px;
left: 0;
position: absolute;
right: 0;
width: 100%;
}
.logo {
display: inline-block;
padding-top: 10px;
padding-right: 15px;
}
</style>
<body>
<div id="header">
<div class="logo"><img src="lightbulb.png" alt="blackout" width="52" height="52"></a><br>
</div>
<strong>Blackout Map</strong> - Lebanon
</div>
<div id="map"></div>
<div id="temp"></div>
<!-- include jquery and highcharts -->
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="https://rawgit.com/highslide-software/highcharts.com/master/js/themes/dark-unica.js"></script>
<!-- include google maps library *before* load cartodb.js -->
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<!-- include your javascripts -->
<script src="main.js"></script>
<script src="temp.js"></script>
</body>
</html>
function main() {
var vis;
// add if you want to select on click and trigger a function
var CLICKLAYER = 1;
// add your url ID here between viz/ and /viz.json
var layerUrl = 'https://team.cartodb.com/u/aureliamoser/api/v2/viz/67f88c2a-b77d-11e4-aae0-0e853d047bba/viz.json';
var options = {
// zoom projection to adjust starting point zoom
zoom: 5,
// set lat/long to center on lebanon
center_lat: 29.90817309627726,
center_lon: 35.5365673828125,
cartodb_logo: false,
layer_selector: true,
}
// layers from your visualization, set them up as vars
var layerIds = {
'pop2000':0,
'epl2009':1,
};
// create map with layers from cartodb editor
cartodb.createVis('map', layerUrl, options)
.done(function(vis, layers) {
console.log(vis, 'layers', layers)
window.vis = vis;
window.overlay = vis.getLayers()[1];
window.layers = layers;
///////////
// pt. 2 continue if you want to select on click to trigger a function
var sublayer = layers[1].getSubLayer(CLICKLAYER);
sublayer.on('featureClick', function(e, pos, latlng, data) {
console.log(e, pos, latlng, data);
$('#temp').show()
})
///////////
})
.on('error', function() {
cartodb.log.log("some error occurred");
});
}
$(main);
// load some temperature data -> high temperature ==> blackouts
// SOURCE:
// http://sdwebx.worldbank.org/climateportal/index.cfm?page=country_historical_climate&ThisRegion=Middle%20East&ThisCCode=LBN#%23
////////////////
// PULLING DATA
////////////////
// You need to patch your jquery request
jQuery.ajaxPrefilter(function(options) {
if (options.crossDomain && jQuery.support.cors) {
options.url = 'http://guarded-ocean-2049.herokuapp.com/' + options.url;
}
});
//Simple helper function to manipulate strings as templates.
function GTemplate(){}
GTemplate.compile = function(template, otag, ctag) {
if(!template) template = '';
var compiled = function(context){
function replaceFn() {
var prop = arguments[1];
return (prop in context) ? context[prop] : '';
}
otag = otag || '{{';
ctag = ctag || '}}';
return template.replace(new RegExp(otag+'(\\w+)'+ctag,'g'), replaceFn);
};
return compiled;
};
// this is the string template we use to construct our requests.
var templateString = "http://{{host}}/climateportal/components/getData.cfc?method=getCCKHistoricalMonthlyCRUPixChart&_cf_ajaxproxytoken={{token}}&returnFormat=json&argumentCollection={{query}}&_cf_nodebug=true&_cf_nocache=true&_cf_rc=31";
// here we are compiling the templateString, we do this only once.
var urlTemplate = GTemplate.compile(templateString);
////////////////
// EXAMPLE USE:
////////////////
// This is the payload for your request, on each click on the map, you would need to
// build this object, from the click you get lat/long, sYear and eYear you get from
// the pull down menu, and type is 1/2 rain/temp.
var payload = JSON.stringify({
lat: 34.19817309627726,
long: 36.1065673828125,
sYear:"1900",
eYear:"2009",
type:2
});
// build url options from payload.
var urlOptions = getURLOptions(payload);
// build url from comiled template.
var url = urlTemplate(urlOptions);
var temp;
function updateTemperature(data){
if(!data || !data.length) return console.error('NO VALID DATA SET');
// make all numbers take one decimal
data = data.map(function(tmp){
return Math.round(tmp * 10) / 10;
});
window.temp.series[0].setData(data);
}
function getURLOptions(payload){
var urlOptions =
{
host:'sdwebx.worldbank.org',
token:"54BF96C2F7AB082C7E975889405CA3D9871063A2CA50D4BAACAD95848B5C73C977",
query: payload
};
return urlOptions;
}
////////////////
// BUILD CHART
////////////////
function setupChart(){
temp = new Highcharts.Chart({
chart: {
renderTo: 'temp'
},
colorAxis: {
},
title: {
text: 'Monthly Average Temperature',
x: -20 //center
},
subtitle: {
text: 'Source: WorldBank.org',
x: -20
},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
yAxis: {
title: {
text: 'Temperature (°C)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: '°C'
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: 'Lebanon',
data: [],
color: '#080b13'
}]
});
}
function loadData(){
// make ajax request using url
$.ajax({
url:url,
type:'GET',
// you need to add this crossDomain property
crossDomain:true,
dataType:'json',
success:function(data){
console.log(data);
updateTemperature(data);
// add some jquery animations to the rendering of the chart
if(! $('#temp').is(":visible")){
$('#temp').show(function(){
// $('#map').animate({height:'58%'});
$('#map').animate({bottom: "36%"});
$('#temp').animate({top: "64%"});
});
google.maps.event.trigger(map, 'resize');
}
},
error:function(xhr, er){
console.log(er);
}
});
}
$(function () {
setupChart();
loadData();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment