在 d3 中获取 featureCollection 的边界

get bounds of featureCollection in d3

从这个要点 https://gist.github.com/mbertrand/5218300 我得到了一些用于绘制某些特征的示例代码,我采用它来使用我的 GeoJSON

var features = [
    { "type": "Feature", "properties": { }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 13.3921498, 52.476596, 31.64 ], [ 13.393036, 52.4765996, 31.6 ], [ 13.3934, 52.4765511, 31.87 ], [ 13.3935847, 52.4765058, 32.37 ], [ 13.3936657, 52.4764735, 32.16 ], [ 13.3936851, 52.4764164, 32.04 ], [ 13.3936229, 52.4761477, 32.05 ], [ 13.3934819, 52.4758929, 32.77 ], [ 13.3932546, 52.4756262, 32.56 ], [ 13.3930283, 52.4754013, 32.51 ], [ 13.3927091, 52.4751468, 32.64 ], [ 13.3923208, 52.4749337, 32.63 ], [ 13.3919094, 52.4747933, 33.13 ], [ 13.3917874, 52.4747948, 32.61 ], [ 13.391795, 52.4747857, 32.75 ], [ 13.3918985, 52.4747159, 33.03 ], [ 13.3921305, 52.4748218, 32.9 ], [ 13.3924295, 52.4749522, 32.21 ], [ 13.392583, 52.475059, 32.49 ], [ 13.3931511, 52.4753106, 32.74 ] ] ] } },
    { "type": "Feature", "properties": { }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 13.3931511, 52.4753106, 32.74 ], [ 13.3934351, 52.475342, 32.43 ] ] ] } }
];

var bounds = d3.geo.bounds(features),
            topLeft = bounds[0],
            bottomRight = bounds[1];

但是在调试脚本时,topLeftbottomRightNaN

我想这是因为我的 JSON 的几何结构更复杂,它由 MultiLineString 几何构成,而不仅仅是简单的 Point 特征。知道如何在这里获得界限吗?

一般来说,接受geojson的D3地理函数只接受geojson对象,不接受数组。如果您将特征嵌套在 FeatureCollection 中,您应该会看到结果:

 var collection = { type: "FeatureCollection", features: features }

var features = [
    { "type": "Feature", "properties": { }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 13.3921498, 52.476596, 31.64 ], [ 13.393036, 52.4765996, 31.6 ], [ 13.3934, 52.4765511, 31.87 ], [ 13.3935847, 52.4765058, 32.37 ], [ 13.3936657, 52.4764735, 32.16 ], [ 13.3936851, 52.4764164, 32.04 ], [ 13.3936229, 52.4761477, 32.05 ], [ 13.3934819, 52.4758929, 32.77 ], [ 13.3932546, 52.4756262, 32.56 ], [ 13.3930283, 52.4754013, 32.51 ], [ 13.3927091, 52.4751468, 32.64 ], [ 13.3923208, 52.4749337, 32.63 ], [ 13.3919094, 52.4747933, 33.13 ], [ 13.3917874, 52.4747948, 32.61 ], [ 13.391795, 52.4747857, 32.75 ], [ 13.3918985, 52.4747159, 33.03 ], [ 13.3921305, 52.4748218, 32.9 ], [ 13.3924295, 52.4749522, 32.21 ], [ 13.392583, 52.475059, 32.49 ], [ 13.3931511, 52.4753106, 32.74 ] ] ] } },
    { "type": "Feature", "properties": { }, "geometry": { "type": "MultiLineString", "coordinates": [ [ [ 13.3931511, 52.4753106, 32.74 ], [ 13.3934351, 52.475342, 32.43 ] ] ] } }
];

var collection = { type: "FeatureCollection", features: features }

var bounds = d3.geo.bounds(collection),
            topLeft = bounds[0],
            bottomRight = bounds[1];
            
console.log(bounds);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>