index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import polygonClipping from 'polygon-clipping';
  2. import { polygon, multiPolygon } from '@turf/helpers';
  3. import { getGeom } from '@turf/invariant';
  4. /**
  5. * Finds the difference between two {@link Polygon|polygons} by clipping the second polygon from the first.
  6. *
  7. * @name difference
  8. * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
  9. * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
  10. * @returns {Feature<Polygon|MultiPolygon>|null} a Polygon or MultiPolygon feature showing the area of `polygon1` excluding the area of `polygon2` (if empty returns `null`)
  11. * @example
  12. * var polygon1 = turf.polygon([[
  13. * [128, -26],
  14. * [141, -26],
  15. * [141, -21],
  16. * [128, -21],
  17. * [128, -26]
  18. * ]], {
  19. * "fill": "#F00",
  20. * "fill-opacity": 0.1
  21. * });
  22. * var polygon2 = turf.polygon([[
  23. * [126, -28],
  24. * [140, -28],
  25. * [140, -20],
  26. * [126, -20],
  27. * [126, -28]
  28. * ]], {
  29. * "fill": "#00F",
  30. * "fill-opacity": 0.1
  31. * });
  32. *
  33. * var difference = turf.difference(polygon1, polygon2);
  34. *
  35. * //addToMap
  36. * var addToMap = [polygon1, polygon2, difference];
  37. */
  38. function difference(polygon1, polygon2) {
  39. var geom1 = getGeom(polygon1);
  40. var geom2 = getGeom(polygon2);
  41. var properties = polygon1.properties || {};
  42. var differenced = polygonClipping.difference(
  43. geom1.coordinates,
  44. geom2.coordinates
  45. );
  46. if (differenced.length === 0) return null;
  47. if (differenced.length === 1) return polygon(differenced[0], properties);
  48. return multiPolygon(differenced, properties);
  49. }
  50. export default difference;