javascript - 在 D3.js 中迭代 geojson 并在满足条件时返回值

标签 javascript d3.js geojson

在 D3.js 中,我尝试遍历 geojson 文件以查找特定属性的值。例如,我想遍历整个 geojson 文件,如果键 state 的值等于 KS,则返回该数据。

我是 D3 的新手,我还没有找到任何可以让我这样做的东西。我的方法可能有缺陷,因此非常感谢任何建议。

{
   "type": "FeatureCollection",
   "features": [{
       "type": "Feature",
       "id": "KDDC",
       "state": "KS",
       "properties": {
          "name": "Dodge City Regional Airport",
          "address": "100 Airport Road, Dodge City, KS, United States"
       },
       "geometry": {
          "type": "Point",
          "coordinates": [
             -99.965556000000007,
             37.763333000000003
          ]
       }
   },

-- 开始代码--

d3.json("airports.json", function(collection) {

   var bounds = d3.geo.bounds(collection),
       path   = d3.geo.path().projection(project);

   path.pointRadius(5);

   var locations = g.selectAll("path")
      .data(collection.features, function(d) {
         if(d.state == "KS"){
            console.log(d.state);
            return d.state;
         }
      })
      .enter()
      .append("path")
      .attr("opacity", 100);

最佳答案

你要做的是array.filter ,然后将其传递给 data() 方法。

例如(您的代码非常接近!)

var locations = g.selectAll("path")
  .data(collection.features.filter(function(d) {
     return d.state == "KS";
  })
  .enter()
  ...

查看 Arrays 上的 d3 API 文档- 它很好地突出了 d3.js 数组功能和常用的内置 javascript 数组功能。

关于javascript - 在 D3.js 中迭代 geojson 并在满足条件时返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13655903/

相关文章:

javascript - 在移动视口(viewport)上隐藏一个居中的标志

javascript - 将创建多少个内部函数副本

javascript - 将平面数组转换为分层数组

javascript - d3.js if else 正则表达式字符串匹配以更改样式

javascript - 在 d3 中渲染铁路数据时奇怪的填充效果

javascript - 如何获取事件按钮 ref 属性并将其分配给 vue.js 中的变量

python - 从 Json 在 Python 中创建具有多个键值的嵌套 Json 结构

javascript - Geojson 渲染问题

javascript - 显示 GeoJson 文件中的一个 map 标记

javascript - 使用外部 JS 的“预期对象”