Skip to content

Instantly share code, notes, and snippets.

@jasonicarter
Last active Nov 10, 2018
Embed
What would you like to do?
Mapping of Toronto Neighbourhoods with TopoJSON and D3.js

Mapping of Toronto Neighbourhoods with TopoJSON and D3.js

  • View on Bl.ocks.org
  • TopoJSON, GeoJSON and Shp files of Toronto neighbourhoods can be found in my repo jasonicarter
<!DOCTYPE html>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://d3js.org/topojson.v1.min.js"></script>
<style type="text/css">
.wrapper {
margin-left: auto;
margin-right: auto;
width: 800px;
}
.map_mesh {
fill: none;
stroke: #fff;
stroke-width: .5px;
stroke-linejoin: round;
}
.map_outline {
fill: #ddd;
stroke: #000;
stroke-width: 1.5px;
}
.map_neighbourhood {
fill: #1f77b4;
}
.map_neighbourhood:hover {
fill: #636363;
cursor: pointer;
}
</style>
<!-- center svg in div -->
<div class="wrapper"></div>
<script>
// With help from - http://bl.ocks.org/michellechandra/0b2ce4923dc9b5809922
var mapWidth = 550,
mapHeight = 550;
var c10 = d3.scale.category10();
var projection = d3.geo.albers();
var path = d3.geo.path()
.projection(projection);
var svg = d3.select(".wrapper").append("svg")
.attr("width", mapWidth)
.attr("height", mapHeight);
var mapLabel = svg.append("text")
.attr("y", 20)
.attr("x", 0)
.attr("class", "map_neighbourhood_name")
// load TopoJSON file
d3.json("toronto_topo.json", function(error, toronto) {
if (error) throw error;
var neighbourhoods = topojson.feature(toronto, toronto.objects.toronto);
// set default projection values
projection
.scale(1)
.translate([0, 0]);
// creates bounding box and helps with projection and scaling
var b = path.bounds(neighbourhoods),
s = .95 / Math.max((b[1][0] - b[0][0]) / mapWidth, (b[1][1] - b[0][1]) / mapHeight),
t = [(mapWidth - s * (b[1][0] + b[0][0])) / 2, (mapHeight - s * (b[1][1] + b[0][1])) / 2];
// set project with bounding box data
projection
.scale(s)
.translate(t);
// get individual neighbourhoods
svg.selectAll("path")
.data(neighbourhoods.features)
.enter().append("path")
.attr("class", "map_neighbourhood")
.attr("d", path)
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", clicked)
// add the mesh/path between neighbourhoods
svg.append("path")
.datum(topojson.mesh(toronto, toronto.objects.toronto, function(a, b) { return a !== b; }))
.attr("class", "map_mesh")
.attr("d", path);
});
function mouseover(d) {
mapLabel.text(d.properties.name.slice(0,-5)) // remove suffix id from name
}
function mouseout(d) {
mapLabel.text("") // remove out name
}
function clicked(d) {
console.log(d.properties.id, d.properties.name) // verify everything looks good
// Add code here
}
</script>
</body>
</html>
Loading
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