index.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import pointInPolygon from '@turf/boolean-point-in-polygon';
  2. import { multiPoint, featureCollection } from '@turf/helpers';
  3. import { featureEach, geomEach, coordEach } from '@turf/meta';
  4. /**
  5. * Finds {@link Points} or {@link MultiPoint} coordinate positions that fall within {@link (Multi)Polygon(s)}.
  6. *
  7. * @name pointsWithinPolygon
  8. * @param {Feature|FeatureCollection<Point|MultiPoint>} points Point(s) or MultiPoint(s) as input search
  9. * @param {FeatureCollection|Geometry|Feature<Polygon|MultiPolygon>} polygons (Multi)Polygon(s) to check if points are within
  10. * @returns {FeatureCollection<Point|MultiPoint>} Point(s) or MultiPoint(s) with positions that land within at least one polygon. The geometry type will match what was passsed in
  11. * @example
  12. * var points = turf.points([
  13. * [-46.6318, -23.5523],
  14. * [-46.6246, -23.5325],
  15. * [-46.6062, -23.5513],
  16. * [-46.663, -23.554],
  17. * [-46.643, -23.557]
  18. * ]);
  19. *
  20. * var searchWithin = turf.polygon([[
  21. * [-46.653,-23.543],
  22. * [-46.634,-23.5346],
  23. * [-46.613,-23.543],
  24. * [-46.614,-23.559],
  25. * [-46.631,-23.567],
  26. * [-46.653,-23.560],
  27. * [-46.653,-23.543]
  28. * ]]);
  29. *
  30. * var ptsWithin = turf.pointsWithinPolygon(points, searchWithin);
  31. *
  32. * //addToMap
  33. * var addToMap = [points, searchWithin, ptsWithin]
  34. * turf.featureEach(ptsWithin, function (currentFeature) {
  35. * currentFeature.properties['marker-size'] = 'large';
  36. * currentFeature.properties['marker-color'] = '#000';
  37. * });
  38. */
  39. function pointsWithinPolygon(points, polygons) {
  40. var results = [];
  41. featureEach(points, function (point) {
  42. var contained = false;
  43. if (point.geometry.type === "Point") {
  44. geomEach(polygons, function (polygon) {
  45. if (pointInPolygon(point, polygon)) contained = true;
  46. });
  47. if (contained) {
  48. results.push(point);
  49. }
  50. } else if (point.geometry.type === "MultiPoint") {
  51. var pointsWithin = [];
  52. geomEach(polygons, function (polygon) {
  53. coordEach(point, function (pointCoord) {
  54. if (pointInPolygon(pointCoord, polygon)) {
  55. contained = true;
  56. pointsWithin.push(pointCoord);
  57. }
  58. });
  59. });
  60. if (contained) {
  61. results.push(multiPoint(pointsWithin));
  62. }
  63. } else {
  64. throw new Error("Input geometry must be a Point or MultiPoint");
  65. }
  66. });
  67. return featureCollection(results);
  68. }
  69. export default pointsWithinPolygon;