使用JS和geojson文件创建nyc行政区的d3地图

时间:2016-03-13 15:44:02

标签: javascript html json d3.js svg

我一直在尝试使用代码创建一个d3地图,用于数周的教程。这是我的HTML代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
  <title></title>
   <script type="text/javascript"  src= "d3.min.js">
      Modernizr.load({
            test: Modernizr.svg && Modernizr.inlinesvg,
            yep : [ 'd3.min.js',
                    'js/script.js' ]
        });
   </script>
</head>

<body>
  <script src="NYC_MapInfo.geojson"></script>

  <script>

   var width = 960, 
       height = 1160;

  var projection = d3.geo.mercator()
      .scale(500)
      .translate([width / 2, height / 2]);

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


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

  d3.json("NYC_MapInfo.geojson", function(error, NYC_MapInfo) {
    svg.append("path")
        .datum(NYC_MapInfo.feature(NYC_MapInfo, NYC_MapInfo.objects))
  .attr("d", path);
});

     </script>
    </body>
</html>

以下是json file的链接:

有人可以帮我修改代码加载图片吗?

这是一个可以帮助您查看代码的链接:http://0.0.0.0:8000/nyc_zipmap.html

1 个答案:

答案 0 :(得分:0)

您正在从GeoJSON文件加载几何体,因此这是绘制这些多边形的方式:

svg.selectAll("path")
   .data(NYC_MapInfo.features)
   .enter()
     .append("path")
     .attr("d", path);

此代码的作用是为geojson文件中“features”下的每个元素创建路径。然后使用您已经拥有的路径功能正确绘制它们。

一旦你这样做,你就会发现你仍然看不到任何东西,那是因为你的地图以世界的错误部分为中心,因此纽约市在你的视口之外。您可以使用d3准确找出您需要放置地图的位置,以及放大多少。但那有点复杂。如此快速的解决方案就是放大你的地图了。

var projection = d3.geo.mercator()
  .scale(10000)
  .translate([width / 2, height / 2]);

然后等待创建路径函数,直到加载GeoJSON。因为那时你可以用d3.geo.centroid函数找到它的中心。

var center = d3.geo.centroid(NYC_MapInfo);
projection.center(center);

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

显示NYC的完整代码是:

<script>

  var width = 960, 
      height = 1160;

  var projection = d3.geo.mercator()
    .scale(10000)
    .translate([width / 2, height / 2]);

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

  d3.json("NYC_MapInfo.geojson", function(error, NYC_MapInfo) {

    // after loading geojson, use d3.geo.centroid to find out 
    // where you need to center your map
    var center = d3.geo.centroid(NYC_MapInfo);
    projection.center(center);

    // now you can create new path function with 
    // correctly centered projection
    var path = d3.geo.path().projection(projection);

    // and finally draw the actual polygons
    svg.selectAll("path")
      .data(NYC_MapInfo.features)
      .enter()
      .append("path")
      .attr("d", path);
  });

</script>

您可能需要摆弄投影中心和比例以正确显示它。 请查看this thread以获取有关如何使用代码执行此操作的更多详细信息。