clusterEach function

void clusterEach(
  1. FeatureCollection<GeometryObject> geojson,
  2. dynamic property,
  3. ClusterEachCallback callback
)

clusterEach Takes a FeatureCollection, a dynamic property key/value used to create clusters, and a ClusterEachCallback method that takes (cluster, clusterValue, currentIndex) and Returns void. For example:

var geojson = FeatureCollection<Point>(features: [
   Feature(
     geometry: Point(coordinates: Position.of([10, 10])),
   ),
   Feature(
     geometry: Point(coordinates: Position.of([20, 20])),
   ),
   Feature(
     geometry: Point(coordinates: Position.of([30, 30])),
   ),
   Feature(
     geometry: Point(coordinates: Position.of([40, 40])),
   ),
 ]);

// Create a cluster using K-Means (adds `cluster` to [GeoJSONObject]'s properties)
var clustered = clustersKmeans(geojson);

// Iterates over each cluster
clusterEach(clustered, 'cluster', (cluster, clusterValue, currentIndex) {
    //= cluster
    //= clusterValue
    //= currentIndex
})

// Calculates the total number of clusters
var total = 0
clusterEach(clustered, 'cluster', function () {
    total++;
});

// Creates [List] of all the values retrieved from the 'cluster' property
var values = []
clusterEach(clustered, 'cluster', (cluster, clusterValue) {
    values.add(clusterValue);
});

Implementation

void clusterEach(
    FeatureCollection geojson, dynamic property, ClusterEachCallback callback) {
  if (property == null) {
    throw Exception("property is required");
  }

  // Creates clusters based on property values
  var bins = createBins(geojson, property);
  var values = bins.keys.toList();
  for (var index = 0; index < values.length; index++) {
    var value = values[index];
    List<int> bin = bins[value]!;
    List<Feature> features = [];
    for (var i = 0; i < bin.length; i++) {
      features.add(geojson.features[bin[i]]);
    }
    callback(FeatureCollection(features: features), value, index);
  }
}