代码之家  ›  专栏  ›  技术社区  ›  rapsak

如何将featurecollection筛选到可与path一起使用的对象。边界()

  •  1
  • rapsak  · 技术社区  · 7 年前

    基于以下示例,我一直在尝试制作具有缩放到边界框功能的地图: https://bl.ocks.org/mbostock/9656675 .

    但对于有岛屿的市镇,缩放将转到选定地块的边界框,而不是市镇的边界框。

    我发现,在我的数据中,有几个区域被水隔开的城市由多个具有相同名称标签的多边形组成,而不是像上面的MikeBostocks示例中那样由一个多多边形组成。

    我设法解决了填充区域的问题,因此如果单击其中一个小岛,错误会变得更加明显,但我不知道如何正确地缩放到市政边界框,而不是陆地区域。

    我试图寻找不同的方法来过滤或子集基于区域名称的featurecollection,但我的解决方案最终都给了我一个错误的数据类型,或者一个从无限到无限的边界框。

    总之,预期的行为是缩放到高亮显示区域的边界框,而不是选定的地块。

    这是我目前的地图: http://plnkr.co/edit/iywWsM9RLs7UzI40q66M?p=preview

    我把变焦的速度减慢了一点,这样更容易发现错误,我希望它不会太烦人。

    这是我怀疑出问题的代码片段。

    function clicked(d) {
    
      if (d.properties.KOMNAVN == kommune) return reset();
      d3.selectAll("path")
        .attr("fill", "teal");
    
      kommune = d.properties.KOMNAVN;
    
      var bounds = path.bounds(d),
        dx = bounds[1][0] - bounds[0][0],
        dy = bounds[1][1] - bounds[0][1],
        x = (bounds[0][0] + bounds[1][0]) / 2,
        y = (bounds[0][1] + bounds[1][1]) / 2,
        scale = Math.max(1, Math.min(zoomExtent, 0.95 / Math.max(dx / w, dy / h))),
        translate = [w / 2 - scale * x, h / 2 - scale * y];
    
      svg.transition()
        .duration(4000)
        .call(zoom.transform, d3.zoomIdentity.translate(translate[0], translate[1]).scale(scale));
    
      d3.selectAll("path").filter(function(d) {
          return d.properties.KOMNAVN == kommune
        })
        .attr("fill", "darkred");
    
    }
    

    提前感谢!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andrew Reid    7 年前

    path.bounds (或 projection.fitSize projection.fitExtent )为此,需要一个geojson对象,该对象可以是功能集合。将此函数馈送到数组将导致问题。

    功能集合如下所示:

    {
       "type":"FeatureCollection",
       "features": features
    }
    

    其中,要素是要素类型的数组。

    您的数据集有一个要素集合,您可以过滤这些要素:

    var filteredFeatures = data.features.filter(function(feature) {
        return feature.properties.property == criteria
    })
    

    然后,可以使用这些过滤的特征创建新的特征集合。在您的情况下,这可能看起来像:

      var filteredFeatures = json.features.filter(function(feature) {
        return feature.properties.KOMNAVN == d.properties.KOMNAVN;
      })
    
      var filteredFeatureCollection = {
        "type":"FeatureCollection",
        "features":filteredFeatures
      }
    

    否,您可以将此新功能集合发送到路径。边界。

    请注意,对于您的示例,我已将click函数移到d3的回调函数中。json使 json 变量包括click函数。

    这是一个 updated plunker.