Skip to content

Instantly share code, notes, and snippets.

@lvngd
Last active June 13, 2020 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lvngd/80a264e20d0874a1a8e34db8a27ef0d0 to your computer and use it in GitHub Desktop.
Save lvngd/80a264e20d0874a1a8e34db8a27ef0d0 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
div#map-container {
width: 800px;
height: 600px;
}
</style>
<body>
<div id="map-container">
<svg></svg>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var width = "800";
var height = "600";
/* colors to fill the nyc borough polygons, lines, subway station points */
var mapFill = "#4f7d7e";
var mapLines = "#fff";
var subwayCircles = "yellow"
var voronoiColor = "#d34528";
var svg = d3.select("svg")
.attr("width", "100%")
.attr("height", "100%");
var generateMap = function(error, nyc,subways) {
if (error) throw error;
var nycMap = svg.append("g")
.attr("class", "nyc-map");
var projection = d3.geoConicConformal();
var path = d3.geoPath()
.projection(projection
.parallels([33, 45])
.rotate([96, -39])
.fitSize([width, height], nyc));
var voronoiLayer = svg.append("g")
.attr("class", "voronoi");
/* draw NYC borough boundaries */
nycMap.selectAll("path")
.data(nyc.features)
.enter().append("path")
.attr("d", path)
.attr("class", "borough-lines")
.attr("stroke", mapLines)
.attr("fill", mapFill);
var voronoi = d3.voronoi()
.x(function(d){return d.coords[0];})
.y(function(d){return d.coords[1];})
.extent([[0,0],[width, height]]);
/* subway station points for voronoi diagram */
var subwayStations = [];
subways.features.forEach(function(d,i){
var projected = projection(d.geometry.coordinates);
var element = {
coords: projection(d.geometry.coordinates),
station: d.properties.line
};
subwayStations.push(element);
});
var polygons = voronoi(subwayStations).polygons();
voronoiLayer.selectAll(".cell")
.data(polygons)
.enter()
.append("path")
.attr("class", "cell")
.attr("fill", "transparent")
.attr("stroke", voronoiColor)
.attr("d", function(d){return "M" + d.join("L") + "Z";});
/* circles for each subway station */
svg.selectAll("circle")
.data(subwayStations).enter()
.append("circle")
.attr("cx", function(d){return d.coords[0];})
.attr("cy", function(d){return d.coords[1];})
.attr("r", "1.5px")
.attr("fill", subwayCircles);
}
d3.queue()
.defer(d3.json, "borough_boundaries.geojson")
.defer(d3.json, "subway_stations.geojson")
.await(generateMap)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment