index.js 1.8 KB

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