d3.js mercator projection to NYC map

2019-05-24 19:00发布

问题:

I am making a map of the boroughs in NYC and I can't seem to get the projection right: the only thing I get is a tiny map.

I tried recreating this example, which only made the console go crazy with errors, I suspect because there was something off about the equation.

When I was trying to get albers to work, I tried out the answer to this question, and still I could not get the map to work.

  With 960/500 height and width, I used: var projection = d3.geo.albers().center([40.71, 73.98]).parallels([29.5, 45.5]).scale(10000).translate([(width) / 2, (height)/2]);

Right now, I am using a transverse Mercator, with the code below, and the topojson I created using one of these files.

  var width = 960,
   height = 500;

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

  d3.json("nyc-borough.json", function(error, nyb) {

  var boroughs = topojson.feature(nyb, nyb.objects["nyc-borough-boundaries-polygon"]).features;

  var projection = d3.geo.transverseMercator()
.scale(1600)
.rotate([73 + 58 / 60, -48 - 47 / 60]);

var path = d3.geo.path()
.projection(projection);

var g = svg.append("g");

g.append("g")
.attr("id", "boroughs")
.selectAll(".state")
.data(boroughs)
.enter().append("path")
.attr("class", function(d){ return d.properties.name; })
.attr("d", path);

});

Please, please halp :(

Thanks in advance!

回答1:

I created a bl.ock with the NYC boroughs here. You were on the right path with WSG84/Mercator as that was what the original data was in, as a quick check in QGIS demonstrated.

QGIS was also good checking the centre of the data, again which came out to be [-73.94, 40.70]. Note that these are the opposite way round to your co-ordinates which were lat and long, but d3 needs long and lat as discussed here in the API. The other thing to look out for is the negatives. North is positive so latitude in the northern hemisphere is positive and negative in the southern hemisphere. For the east and west hemispheres its east that's positive. Of course this only matters for the global projections the USA Albers wouldn't have negatives for the USA. Oh, and no discussion on Projections would be complete without a look at Jason Davies work.

If you want to use a different projection to the projection your data is in I generally think it's better to preprocess your data into that projection and QGIS is a great tool for that but there are many others such as gdal.