繁体   English   中英

使用Mapbox GL JS计数出现次数(geojson属性)

[英]Count ocurrences using Mapbox GL JS (geojson properties)

我需要一种方法来为geojson文件的每个要素计数相同的属性,并获得如下所示的数组:array = [“ type 1”,“ type 2”,“ type 3”,“ type 2”,“ type 1” ,“类型2”,“类型1”,“类型3”,“类型1”,“类型1”,....]

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

这实际上不是mapbox-gl问题。 您的GeoJson只是标准的JavaScript对象, features是标准的Array:

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
}, {});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM