index.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import turfbbox from "@turf/bbox";
  2. import booleanPointInPolygon from "@turf/boolean-point-in-polygon";
  3. import rbush from "rbush";
  4. /**
  5. * Merges a specified property from a FeatureCollection of points into a
  6. * FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty`
  7. * for polygons, this finds every point that lies within each polygon, collects the
  8. * `inProperty` values from those points, and adds them as an array to `outProperty`
  9. * on the polygon.
  10. *
  11. * @name collect
  12. * @param {FeatureCollection<Polygon>} polygons polygons with values on which to aggregate
  13. * @param {FeatureCollection<Point>} points points to be aggregated
  14. * @param {string} inProperty property to be nested from
  15. * @param {string} outProperty property to be nested into
  16. * @returns {FeatureCollection<Polygon>} polygons with properties listed based on `outField`
  17. * @example
  18. * var poly1 = turf.polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]);
  19. * var poly2 = turf.polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]);
  20. * var polyFC = turf.featureCollection([poly1, poly2]);
  21. * var pt1 = turf.point([5,5], {population: 200});
  22. * var pt2 = turf.point([1,3], {population: 600});
  23. * var pt3 = turf.point([14,2], {population: 100});
  24. * var pt4 = turf.point([13,1], {population: 200});
  25. * var pt5 = turf.point([19,7], {population: 300});
  26. * var pointFC = turf.featureCollection([pt1, pt2, pt3, pt4, pt5]);
  27. * var collected = turf.collect(polyFC, pointFC, 'population', 'values');
  28. * var values = collected.features[0].properties.values
  29. * //=values => [200, 600]
  30. *
  31. * //addToMap
  32. * var addToMap = [pointFC, collected]
  33. */
  34. function collect(polygons, points, inProperty, outProperty) {
  35. var rtree = rbush(6);
  36. var treeItems = points.features.map(function (item) {
  37. var _a;
  38. return {
  39. minX: item.geometry.coordinates[0],
  40. minY: item.geometry.coordinates[1],
  41. maxX: item.geometry.coordinates[0],
  42. maxY: item.geometry.coordinates[1],
  43. property: (_a = item.properties) === null || _a === void 0 ? void 0 : _a[inProperty],
  44. };
  45. });
  46. rtree.load(treeItems);
  47. polygons.features.forEach(function (poly) {
  48. if (!poly.properties) {
  49. poly.properties = {};
  50. }
  51. var bbox = turfbbox(poly);
  52. var potentialPoints = rtree.search({
  53. minX: bbox[0],
  54. minY: bbox[1],
  55. maxX: bbox[2],
  56. maxY: bbox[3],
  57. });
  58. var values = [];
  59. potentialPoints.forEach(function (pt) {
  60. if (booleanPointInPolygon([pt.minX, pt.minY], poly)) {
  61. values.push(pt.property);
  62. }
  63. });
  64. poly.properties[outProperty] = values;
  65. });
  66. return polygons;
  67. }
  68. export default collect;