在d3.js中绘制已经投影的geoJSON映射

时间:2013-02-01 12:47:43

标签: d3.js geojson

使用d3.js的v3,我在使用geoJSON数据绘制地图时遇到问题。代码和生成的地图显示在:http://bl.ocks.org/73833ec90a8a77b0e29f。使用d3.js的v2,此示例生成正确的映射。

  1. 我的数据已经预测(它们是Dutch National Grid / Rijksdriehoekstelsel坐标)。为了弥补这一点,我编写了自己的投影函数,它只是将地图的坐标系转换为像素(例如缩放和平移)。
  2. d3.js v3中的
  3. d3.geo.path()重新采样数据。但是,重新采样中生成的点似乎与我的地图在同一坐标系中(我假设它们是lon,lat坐标)。
  4. 我宁愿不将地图的坐标转换为lon,lat坐标,因为地图已经按照我想要的方式进行投影,据我所知,这不是一个微不足道的投影。

    如果问题确实是由重采样引起的,我想禁用重采样。但是,在文档中我真的找不到如何做到这一点。我可以传递一个流对象,而不是将投影函数传递给d3.geo.path.projection()。我认为以下内容可行:

    var projection = d3.geo.projection(function(x, y) {
        return [ scale*(x-xmin), height-scale*(y-ymin) ];
      }).precision(0);
    

    但事实并非如此。可能也与我没有lat,lon坐标的事实有关。如何使用自定义投影功能禁用重采样?

    或者当其他事情导致问题时,我想听听。

    感谢。

2 个答案:

答案 0 :(得分:7)

我最近遇到了同样的问题。

这样做的方法是明确告诉d3你不想要投影。 答案在于link

"If projection is null, the path uses the identity transformation, where the input 
geometry is not projected and is instead rendered directly in raw coordinates. This can be 
useful for fast rendering of already-projected geometry, or for fast rendering of the 
equirectangular projection."

所以你想拥有

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

然后,就像这样

g.selectAll("path")
            .data(json.features)
            .enter().append("path")
            .attr("d", path)

答案 1 :(得分:6)

为了回应user603124的回答,我又看了一下这个问题(到现在为止,我坚持使用d3.js的v2)。我创建对象的最初想法是有效的。但是,在我原来的实现中,我缩放和缩放错误。使用answer to another question进行缩放和缩放:

<script>
  var height = 400;
  var width  = 400;

  var vis = d3.select("#vis").append("svg")
      .attr("width", width).attr("height", height)

  d3.json("po_2012_simplified.json", function(json) {

      var projection = d3.geo.projection(function(x, y) { return [x, y];})
        .precision(0).scale(1).translate([0, 0]);

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

      var bounds = path.bounds(json),
          scale  = .95 / Math.max((bounds[1][0] - bounds[0][0]) / width, 
                  (bounds[1][1] - bounds[0][1]) / height),
          transl = [(width - scale * (bounds[1][0] + bounds[0][0])) / 2, 
                  (height - scale * (bounds[1][1] + bounds[0][1])) / 2];

      projection.scale(scale).translate(transl);

      vis.selectAll("path").data(json.features).enter().append("path")
        .attr("d", path)
        .style("fill", "#D0D0D0")
        .style("stroke-width", "0.5px")
        .style("stroke", "black")
    });

</script>

有关完整的解决方案,请参阅http://bl.ocks.org/djvanderlaan/5336035

相关问题