簡體   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