Search code examples
d3.jsgeolocationmaps

Plot New York neighborhoods with d3.js


I am trying to create a New York neighborhoods map with d3.js.

I downloaded the file from here https://www1.nyc.gov/site/planning/data-maps/open-data/dwn-nynta.page

Then I drop the shapefile into http://mapshaper.org/ and simplify it to 1%. Finally I export it as a topojson.

Now, I am using the following d3.js code and I get random lines.

enter image description here

<!DOCTYPE html>
<meta charset="utf-8">

<style type="text/css">
  body {
    font-family: arial, sans;
    font-size: 14px;
    width: 960px;
    margin: 40px auto;
  }
  .ny-neighborhoods {
    stroke: #000;
    stroke-width: .50;
    fill: none;
  }
</style>

<body>
<div id="chart-container"></div>
</body>

<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/topojson.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/queue-async/1.0.7/queue.min.js"></script>

<script type="text/javascript">

var margin = {top: 5, right: 5, bottom: 5, left: 5};
var width = 900 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

queue()
    //.defer(d3.csv, "sales.csv")
    .defer(d3.json, "nynta.json")
    .await(ready);

function ready(error, data, ny) {
  if (error) return console.warn(error);
  console.log(ny)
  //data.forEach(function(d) {
        //d.val = +d.val;
      //});
  var nyfeatures = topojson.feature(ny,ny.objects.nynta)
  console.log(nyfeatures)
  var svg = d3.select("#chart-container")
    .append("svg")
      .attr("class", "map")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
    .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
  var path = d3.geoPath()
      .projection(d3.geoAlbersUsa()
      .fitSize([width, height], nyfeatures));
  var nyPaths = svg.selectAll(".ny-neighborhoods")
      .data(nyfeatures.features)
    .enter().append("path")
      .attr("class", "ny-neighborhoods")
      .attr("d", function(d) { return path(d); })
}
</script>

Solution

  • Thanks to the amazing effort and time investment of @elias, we figured out that the shapefile didn't work. Instead we used the geojson and simplified that in mapshaper.org to export it as a topojson.

    One hint for future usage - when you do that, you probably will save it under a new filename, so it will change your features hierarchy

    var nyfeatures = topojson.feature(ny,ny.objects.newyork)
    

    Thank You very much, it looks now like this:

    enter image description here