d3 world map — calculate geo bounds on zoom

本小妞迷上赌 提交于 2019-12-08 15:31:31

My other answer was a misreading of the question, but I'll leave it there in case someone else misreads the question in the same way.

To find the bounding box of the visual area of your map on screen, simply use the projection.invert() function and feed it the top-left and bottom-right corners of your SVG. If you have a 500x500 SVG, then that looks like this:

 projection.invert([0,0])
 projection.invert([500,500])

This is a bounding box of your screen, in lat-long (or whatever coordinate system you're using).

After that, you can get the bounds of your features and test to see if they are fully-contained or intersecting or have their centroid within those bounds. I'm not going to explain how to do that here, because that's a different question with many different answers depending on which definition of "within these bounds" you decide on.

I'm not aware of any built in functionality to give the bounds of a set of features, but here's a pretty simple function that does that:

function boundingExtent(features) {
  var boundExtent = [[0,0],[0,0]];
  for (var x in features) {
    thisBounds = d3.geo.bounds(features[x]);
    boundExtent[0][0] = Math.min(thisBounds[0][0],boundExtent[0][0]);
    boundExtent[0][1] = Math.min(thisBounds[0][1],boundExtent[0][1]);
    boundExtent[1][0] = Math.max(thisBounds[1][0],boundExtent[1][0]);
    boundExtent[1][1] = Math.max(thisBounds[1][1],boundExtent[1][1]);
  }
  return boundExtent;
}

With that, you can just pass the array of features to boundingExtent(featureArray) and it will give you back a bounding box for your entire set.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!