d3和Leaflet之间的GeoJSON映射差异

5

我的目标是使用d3为给定的GeoJSON功能集生成SVG路径。

当我使用leaflet映射这些路径时,所有的功能看起来都很完美。

d3.json("ct_counties.geo.json", function(data) {
    var leaflet_paths = leaflet_map.addLayer(new L.GeoJSON(data));
});

two maps

然而,使用d3进行路径映射时,部分特征看起来是错误的。

d3.json("ct_counties.geo.json", function(collection) {
    var bounds = d3.geo.bounds(collection);

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

    var feature = g.selectAll("path")
        .data(collection.features)
      .enter().append("path")
        .attr('class','county');

    d3_map.on("viewreset", reset);

    reset();

    function project(x) {
      var point = d3_map.latLngToLayerPoint(new L.LatLng(x[1], x[0]));
      return [point.x, point.y];
    }

    function reset() {
      var bottomLeft = project(bounds[0]); 
      var topRight = project(bounds[1]);
      svg.attr("width", topRight[0] - bottomLeft[0])
        .attr("height", bottomLeft[1] - topRight[1])
        .style("margin-left", bottomLeft[0] + "px")
        .style("margin-top", topRight[1] + "px");
      g.attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")");
      feature.attr("d", path);
    }
});

在此查看地图差异。

并且请参考完整代码

由于两个地图使用相同的要素集合,为什么d3版本是错误的?


3
看起来多边形的解释不同,可能是由于点的顺序不同。仔细检查后,似乎每个多边形都缺少一个点。可能是因为结尾与开头粘合的部分有问题? - flup
1个回答

23

D3并没有错,数据是错误的,而Leaflet则更加宽容。

以利奇菲尔德(左上角县)为例:

{
    "type" : "Feature",
    "properties" : {
        "kind" : "county",
        "name" : "Litchfield",
        "state" : "CT"
    },
    "geometry" : {
        "type" : "MultiPolygon",
        "coordinates" : [ [ [ [ -73.0535, 42.0390 ], [ -73.0097, 42.0390 ],
                [ -73.0316, 41.9678 ], [ -72.8892, 41.9733 ],
                [ -72.9385, 41.8966 ], [ -72.9495, 41.8090 ],
                [ -73.0152, 41.7981 ], [ -72.9823, 41.6392 ],
                [ -73.1631, 41.5571 ], [ -73.1576, 41.5133 ],
                [ -73.3219, 41.5078 ], [ -73.3109, 41.4694 ],
                [ -73.3876, 41.5133 ], [ -73.4424, 41.4914 ],
                [ -73.4862, 41.6447 ], [ -73.5191, 41.6666 ],
                [ -73.4862, 42.0500 ] ] ] ]
    }
}
多边形不是封闭的,它的结尾与开头不相等。我标出了坐标,并将第一个坐标标记为红色,最后一个坐标标记为绿色:points in the multipolygon 正如您所看到的,d3会丢弃最后一个坐标。
根据GeoJSON规范
引用:

LinearRing 是一个由4个或更多位置组成的封闭LineString。 第一个和最后一个位置是等价的(它们代表等价点)。

所以,d3有一点(没有话题),应该在末尾添加起始坐标来关闭MultiPolygon:
...[ -73.4862, 42.0500 ], [ -73.0535, 42.0390 ] ] ] ]

感谢@flup。澄清一点:我并不是在说d3作为一个框架是错的;相反,我是在指我的d3地图实现。 - s2t2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接