d3 world map — calculate geo bounds on zoom

▼魔方 西西 提交于 2019-12-23 02:48:46

问题


I am trying to adapt Mike Bostock's constrained zoom example to fit my needs. (http://bl.ocks.org/mbostock/4987520). Is there any way to calculate the geo bounds (in long/lat) of the projection when the map is zoomed. The d3.geo.bounds() method expects a 'feature' -- I really don't want to zoom on any particular feature. All I want is the geo bounds for the visible area of the projection.

Thanks in advance, Kishore


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/25831103/d3-world-map-calculate-geo-bounds-on-zoom

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