block by fil 8090c35ded3e46368843dfed82543617

New York Centroid Fixed

Full Screen

Fix for d3-geo issue #81.

forked from mbostock‘s block: New York Centroid Test

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3-geo.js"></script>
<script>


var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height");

var projection = d3.geoMercator(),
    path = d3.geoPath(projection);

var color = d3.scaleOrdinal(d3.schemeCategory10);

d3.json("ny.json", function(error, ny) {
  if (error) throw error;

  var centroids = ny.features.map(d3.geoCentroid),
  centroid = d3.geoCentroid(ny);


  projection.fitExtent([[10, 10], [width - 10, height - 10]], {
    type: "FeatureCollection",
    features: ny.features.concat({
      type: "Feature",
      geometry: {
        type: "MultiPoint",
        coordinates: [centroid, ...centroids]
      }
    })
  });

  svg.selectAll('path')
  .data(ny.features)
  .enter()
  .append("path")
      .attr("fill", (d,i) => color(i))
      .attr("fill-opacity", 0.2)
      .attr("stroke", (d,i) => color(i))
      .attr("d", path);

  svg.selectAll('circle')
  .data(centroids)
  .enter()
  .append("circle")
      .attr("transform", d => "translate(" + projection(d) + ")")
      .attr("r", 5)
      .attr("fill", (d,i) => color(i))
      .attr("fill-opacity", 0.2)
      .attr("stroke", (d,i) => color(i));

  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", 2)
      .attr("fill", "orange")
      .attr("stroke", "white");




});


</script>