index.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { multiPolygon, polygon, } from "@turf/helpers";
  2. import { getGeom } from "@turf/invariant";
  3. import polygonClipping from "polygon-clipping";
  4. /**
  5. * Takes two {@link Polygon|polygon} or {@link MultiPolygon|multi-polygon} geometries and
  6. * finds their polygonal intersection. If they don't intersect, returns null.
  7. *
  8. * @name intersect
  9. * @param {Feature<Polygon | MultiPolygon>} poly1 the first polygon or multipolygon
  10. * @param {Feature<Polygon | MultiPolygon>} poly2 the second polygon or multipolygon
  11. * @param {Object} [options={}] Optional Parameters
  12. * @param {Object} [options.properties={}] Translate GeoJSON Properties to Feature
  13. * @returns {Feature|null} returns a feature representing the area they share (either a {@link Polygon} or
  14. * {@link MultiPolygon}). If they do not share any area, returns `null`.
  15. * @example
  16. * var poly1 = turf.polygon([[
  17. * [-122.801742, 45.48565],
  18. * [-122.801742, 45.60491],
  19. * [-122.584762, 45.60491],
  20. * [-122.584762, 45.48565],
  21. * [-122.801742, 45.48565]
  22. * ]]);
  23. *
  24. * var poly2 = turf.polygon([[
  25. * [-122.520217, 45.535693],
  26. * [-122.64038, 45.553967],
  27. * [-122.720031, 45.526554],
  28. * [-122.669906, 45.507309],
  29. * [-122.723464, 45.446643],
  30. * [-122.532577, 45.408574],
  31. * [-122.487258, 45.477466],
  32. * [-122.520217, 45.535693]
  33. * ]]);
  34. *
  35. * var intersection = turf.intersect(poly1, poly2);
  36. *
  37. * //addToMap
  38. * var addToMap = [poly1, poly2, intersection];
  39. */
  40. export default function intersect(poly1, poly2, options) {
  41. if (options === void 0) { options = {}; }
  42. var geom1 = getGeom(poly1);
  43. var geom2 = getGeom(poly2);
  44. var intersection = polygonClipping.intersection(geom1.coordinates, geom2.coordinates);
  45. if (intersection.length === 0)
  46. return null;
  47. if (intersection.length === 1)
  48. return polygon(intersection[0], options.properties);
  49. return multiPolygon(intersection, options.properties);
  50. }