使用Mapbox GL JS计算发生次数(geojson属性)

时间:2018-03-20 12:57:28

标签: javascript mapbox mapbox-gl-js

我需要一种方法来为geojson文件的每个特征计算相同的属性并获得如下数组:array = [" type 1"," type 2",& #34;类型3","类型2","类型1","类型2","类型1",& #34;类型3","类型1","类型1",....]

我正在从文件中加载大型geojson要素集。

1 个答案:

答案 0 :(得分:0)

这不是一个mapbox-gl问题。您的GeoJson只是标准的JavaScript对象,features是标准的数组:

const counts = new Map();

for (const feature of geojson.feature) {
  const alert = feature.properties.alert;

  if (!alert) {
    continue;
  }

  if (!counts.has(alert)) {
    counts.set(alert, 0);
  }

  const currentCount = counts.get(alert);
  counts.set(alert, currentCount + 1);
}

// counts will look like this
Map(
  "type1" -> 10,
  "type2" -> 8,
  "type3" -> ...
)

或者更简洁:

const counts = geojson.features.reduce((accumulatedCounts, feature) => {
  const alert = feature.properties.alert;

  if (!alert) return accumulatedCounts;
  if (!accumulatedCounts[alert]) accumulatedCounts[alert] = 0;

  accumulatedCounts[alert]++;

  return accumulatedCounts
}, {});