turf.collect
What is turf.collect?
turf.collect performs a spatial aggregation: for every polygon, it finds the points that fall inside it and collects a named property from those points into an array on the polygon.
turf.collect(polygons, points, inProperty, outProperty) → FeatureCollection<Polygon>Parameters:
polygons— FeatureCollection of Polygonspoints— FeatureCollection of PointsinProperty— property name on each point to readoutProperty— property name on each polygon to write (an array)
When would you use turf.collect?
Use turf.collect whenever you need per-polygon summaries of point attributes — total sales per neighbourhood, lists of incident IDs per precinct, or arrays of sensor readings per catchment. After collecting, run ordinary JavaScript (.reduce, .length, averages) on each polygon's array to produce the statistic you need.
It is especially convenient with grid helpers: collect point values into hexGrid or squareGrid cells, then style the cells by the resulting array length or sum for a quick choropleth.
1const withTotals = turf.collect(hexes, sales, 'amount', 'amounts');
2withTotals.features.forEach(h => {
3 const arr = h.properties.amounts;
4 h.properties.total = arr.reduce((s, v) => s + v, 0);
5});FAQs
How do I install Turf.js to use this function?
Install npm install @turf/collect and import import { collect } from '@turf/collect'. It is also exposed via turf.collect on @turf/turf.
What happens to polygons with no points inside?
They receive an empty array at outProperty. Filter or default to [] before aggregating to avoid .reduce errors on undefined.
Is turf.collect faster than a manual loop?
Internally it still tests each point against each polygon — O(n × m) — so for very large datasets consider pre-indexing points with a spatial tree (e.g. rbush) and querying per polygon. For moderate sizes it is plenty fast and much more concise than rolling your own.
When should I prefer turf.tag instead?
Use turf.tag when you want one value per point (its containing polygon id). Use turf.collect when you want one array per polygon. They are complementary directions of the same spatial join.