Skip to content

Instantly share code, notes, and snippets.

@jmharkins
Last active April 16, 2016 03:00
Show Gist options
  • Save jmharkins/3e15923047cc18f7455949accec910d6 to your computer and use it in GitHub Desktop.
Save jmharkins/3e15923047cc18f7455949accec910d6 to your computer and use it in GitHub Desktop.
NYC Map - Distance between Census Tracts by Color

Mapping distance between census tracts using d3.geo.distance between the two centroids. Click on a census tract to show distance for all others by color.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.tpath {
/*fill:#ccc;*/
stroke:#ccc
}
.census-centr-on {
fill:red;
}
.census-centr-off {
fill:none;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<script src="map.js"></script>
var width = 750,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var test;
d3.json("nyccensus.json", function(error, nyc) {
if (error) {return console.error(error)}
var subunits = topojson.feature(nyc, nyc.objects.census)
test = subunits;
//
var projection = d3.geo.mercator()
.center([-73.94, 40.70])
.scale(50000)
.translate([width / 2, height / 2])
//
var path = d3.geo.path()
.projection(projection);
//
features = subunits.features
features.forEach(function(feature, i) {
feature.centroid = path.centroid(feature);
if (feature.centroid.some(isNaN)) feature.centroid = null; // off the map
});
color = d3.scale.sqrt()
.domain([0,0.007])
// .range(["#deebf7","#08306b"])
.range(["#fff","#000"])
var tracts = svg.selectAll('.tcontainer')
.data(features)
.enter()
.append("g")
.attr('class','tcontainer')
.append("path")
.attr('class','tpath')
.attr("d", path)
.attr("fill",'#fff')
.on("click", function(d){
dcenter(this.parentNode)
});
function dcenter(tct) {
reset();
var hl_circ = d3.select(tct).selectAll('circle')
.attr('class','census-centr-on');
var ref_coord = projection.invert(hl_circ.datum().centroid);
tracts = set_new_loc(ref_coord)
}
function reset() {
d3.selectAll('.census-centr-on')
.attr('class','census-centr-off');
}
function set_new_loc(coords) {
d3.selectAll('.tpath')
.attr('fill',function(d){
return color(d3.geo.distance(coords,projection.invert(d.centroid)))
})
}
var dots = svg.selectAll('.tcontainer')
.append('circle')
.attr('class','census-centr-off')
.attr('transform',function(d){
return 'translate (' + d.centroid[0] + ',' +d.centroid[1] + ')'
})
.attr('r',2)
})
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment