Skip to content

Instantly share code, notes, and snippets.

@mbostock
Created February 14, 2017 15:37
New York Centroid Test
<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var projection = d3.geoMercator(),
path = d3.geoPath(projection);
d3.json("ny.json", function(error, ny) {
if (error) throw error;
var centroid = d3.geoCentroid(ny);
projection.fitExtent([[10, 10], [width - 10, height - 10]], {
type: "FeatureCollection",
features: ny.features.concat({
type: "Feature",
geometry: {
type: "Point",
coordinates: centroid
}
})
});
svg.append("path")
.attr("fill", "black")
.attr("fill-opacity", 0.2)
.attr("stroke", "black")
.attr("d", path(ny));
svg.append("circle")
.attr("transform", "translate(" + path.centroid(ny) + ")")
.attr("r", 5)
.attr("fill", "red")
.attr("stroke", "white");
svg.append("circle")
.attr("transform", "translate(" + projection(centroid) + ")")
.attr("r", 5)
.attr("fill", "blue")
.attr("stroke", "white");
});
</script>
Raw
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