Skip to content

Instantly share code, notes, and snippets.

@clhenrick
Last active August 29, 2015 14:20
Show Gist options
  • Save clhenrick/cf235ecdbf5612a7ef6b to your computer and use it in GitHub Desktop.
Save clhenrick/cf235ecdbf5612a7ef6b to your computer and use it in GitHub Desktop.
handlebars templating using cartodb.js, cartodb sql api, nyc geoclient api, aja.js
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#map {
width:50%;
height: 100%;
float: right;
}
.tr-modal {
width: 50%;
height:100%;
float: left;
}
</style>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.14/themes/css/cartodb.css" />
</head>
<body>
<div class="tr-modal">
</div>
<div id="map"></div>
<script id="org-template" type="text/x-handlebars-template">
<div class="org-container">
<h1>
Here are some groups that help people with housing
issues in your neighborhood:
</h1>
{{#each orgs}}
<div class="tr-org-info">
<h3>{{name}}</h3>
<p class="website-url"><span>website: </span>{{website}}</p>
<p class="phone-no"><span>phone: </span>{{phone}}</p>
<p class="address"><span>address: </span>{{address}}</p>
<p class="email"><span>email: </span>{{email}}</p>
<p class="description">{{description}}</p>
</div>
{{/each}}
</div>
</script>
</body>
<!--
<script src="../js/vendor/aja.min.js"></script>
<script src="../js/tmp/get-tenants-rights-group.js"></script>
-->
<script src="https://rawgit.com/krampstudio/aja.js/1ef8622dc808188944a5d47eeda64a00cbd88164/aja.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.2/handlebars.js"></script>
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.14/cartodb.js"></script>
<script>
// set up the leaflet / cartodb map
var d = document;
var w = window;
var addressMarker;
var el = {};
var g = {};
var a = aja;
var sqlURL = "https://chenrick.cartodb.com/api/v2/sql?q=";
var trmodal = d.getElementsByClassName('tr-modal')[0];
var source = $("#org-template").html();
var template = Handlebars.compile(source);
Handlebars.registerHelper('each', function(context, options) {
var ret = "";
for(var i=0, j=context.length; i<j; i++) {
ret = ret + options.fn(context[i]);
}
return ret;
});
var initMap = function() {
el.map = new L.Map('map', {
center : [40.7127, -74.0059],
zoom : 12
// dragging : false,
// touchZoom : false,
// doubleClickZoom : false,
// scrollWheelZoom : false,
// zoomControl : false,
// keyboard : false
});
var basemap = L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png',{
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
});
var cdbURL = 'https://chenrick.cartodb.com/api/v2/viz/3680af8e-7816-11e4-ab90-0e4fddd5de28/viz.json';
var cartocss = "#all_map_pluto_rent_stabl_reg_2014v1 {" +
"polygon-fill: #FF6600;" +
"polygon-opacity: 0.6;" +
"line-color: #000;" +
"line-width: 0.7;" +
"line-opacity: 0.3;" +
"}";
var sql = 'SELECT the_geom, the_geom_webmercator, cartodb_id, address, borough, ownername, unitsres ' +
'FROM all_nyc_likely_rent_stabl_merged';
var taxLots;
el.map.addLayer(basemap);
cartodb.createLayer(el.map, cdbURL, {
cartodb_logo: false,
legends: false,
https: true,
fullscreen : true
},
function(layer) {
taxLots = layer.getSubLayer(0);
taxLots.setCartoCSS(cartocss);
// taxLots.setSQL(sql);
// taxLots.setInteraction(true);
// taxLots.setInteractivity('address, borough, unitsres, ownername');
// taxLots.on('click', function(e, pos, latlng, data){
// console.log('data: ', data);
// });
el.map.addLayer(layer, false);
basemap.bringToBack();
})
// .addTo(el.map)
.done(function(layer){
// console.log(layer);
// basemap.bringToBack();
});
}; // end initMap()
/**************************/
// grab property data from nyc geo-client api
var geoclient = function(num, name, boro) {
// create URL to pass to geoclient api
var id = '9cd0a15f',
appID = 'app_id=' + id + '&',
key = '54dc84bcaca9ff4877da771750033275',
appKey = 'app_key=' + key,
stNum = 'houseNumber='+ num + '&',
nameEncoded = name.replace(' ', '+'),
stName = 'street=' + nameEncoded + '&',
borough = 'borough=' + boro + '&',
url = 'https://api.cityofnewyork.us/geoclient/v1/address.json?',
urlConcat = url + stNum + stName + borough + appID + appKey;
getJSON(urlConcat, 'jsonp', checkResult);
};
// see if the geolient result has a bbl
function getJSON(url, type, callback) {
a().url(url)
.type(type)
.on('success', function(data){
callback(data);
})
.on('error', function(err){
callback('error');
})
.go();
}
function checkResult(data) {
if (typeof data === "object" && data.address.bbl !== undefined ) {
var d = data.address;
g = {
bbl : d.bbl,
lon : d.longitudeInternalLabel,
lat : d.latitudeInternalLabel,
hNo : d.houseNumber,
sName : d.streetName1In,
bCode : d.boroughCode1In,
bUSPS : d.uspsPreferredCityName,
zip : d.zipCode,
cd: d.communityDistrict,
bin : d.giBuildingIdentificationNumber1,
tr_groups : []
};
var bbl = d.bbl;
var gcr_stringify = JSON.stringify(g);
// _gaq.push(['_trackEvent', 'Geoclient Success', 'Result', gcr_stringify]);
getCDBdata(bbl);
showMarker(data);
// } else {
// el.addressInput.value='';
// f.resetBoroValue();
// if (f.hasClass(el.valErrorNF, 'vis-hidden')===true) {
// f.toggleClass(el.valErrorNF, 'vis-hidden');
// }
// if (f.hasClass(el.valErrorBoro, 'vis-hidden')===false) {
// f.addClass(el.valErrorBoro, 'vis-hidden');
// }
// if (f.hasClass(el.valErrorAddress, 'vis-hidden')===false) {
// f.addClass(el.valErrorAddress, 'vis-hidden');
// }
// app.events.publish('state-change', { formFilled : false });
// app.f.goToPrevSlide();
}
};
function trQuery(lat, lon) {
// construct the tenants rights group query
var query = "SELECT * FROM nyc_tenants_rights_service_areas " +
"WHERE " +
"ST_Contains(" +
"nyc_tenants_rights_service_areas.the_geom," +
"ST_GeomFromText(" +
"'Point(" + lon + " " + lat + ")', 4326" +
")" +
");";
return query;
}
// check the bbl number against the cartodb data
var getCDBdata = function(bbl) {
// sql to pass cartodb's sql api
var sql1 = "SELECT bbl FROM map_pluto_likely_rs " +
"WHERE bbl = " + bbl;
var sql2 = trQuery(g.lat, g.lon);
getJSON(sqlURL + sql1, 'json', checkRS);
getJSON(sqlURL + sql2, 'json', checkTR);
};
function checkRS(data) {
if (data.rows.length > 0 && state.yesNoState === false) {
console.log('rs === true');
// var bbl_match = JSON.stringify(data.rows[0].bbl);
// _gaq.push(['_trackEvent', 'CDB', 'Match', bbl_match]);
// app.f.toggleClass(el.yes, 'hidden');
// app.f.toggleClass(el.no, 'hidden');
// app.events.publish('state-change', { yesNoState : true });
}
// f.goToNextSlide();
}
// check for tenants rights groups
function checkTR(data) {
var noTR = d.querySelector('.no-local-tr');
var yesTR = d.querySelector('.yes-local-tr');
// var ul = d.createElement('ul');
// ul.className = 'org-list';
hbData = {orgs : []};
if (data.rows.length > 0) {
var i = 0, l = data.rows.length;
for (i; i<l; i++) {
var x = data.rows[i];
g.tr_groups.push(x);
hbData.orgs.push(handlebarsMake(x));
console.log('org data: ', x);
}
var html = template(hbData);
trmodal.innerHTML = html;
}
}
function handlebarsMake(data) {
var context = {
name: data.name,
website: data.website_url,
phone: data.phone,
email: data.email,
address: data.address,
description: data.description
};
// var html = template(context);
return context;
}
function handlebarsTest() {
var context = {
name: '',
website: '',
phone: '',
email: '',
address: '',
description: ''
};
var html;
context.name = 'Test Org';
context.website = 'http://example.com';
context.phone = '(555) 555 - 5555';
context.email = 'example@gmail.com';
context.address = '123 Memory Lane, Brooklyn, NY 11225';
context.description = 'A test description bla bla bla...';
html = template(context);
el.trmodal.innerHTML = html;
}
var showMarker = function(data) {
// console.log('showMarker data: ', data);
var x = data.address.longitudeInternalLabel,
y = data.address.latitudeInternalLabel,
latlng = [y, x],
address = data.address.houseNumber + ' ' +
data.address.firstStreetNameNormalized + '<br>' +
data.address.uspsPreferredCityName + ', NY ' +
data.address.zipCode;
// remove geocoded marker if one already exists
if (addressMarker) {
el.map.removeLayer(addressMarker);
}
// add a marker and pan and zoom the el.map to it
addressMarker = new L.marker(latlng).addTo(el.map);
addressMarker.on('popupopen', function(e){
el.map.setView(latlng, 16);
});
addressMarker.bindPopup("<b>" + address + "</b>").openPopup();
};
$(document).ready(function(){
initMap();
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment