index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import polygonClipping from "polygon-clipping";
  2. import { getGeom } from "@turf/invariant";
  3. import { multiPolygon, polygon } from "@turf/helpers";
  4. /**
  5. * Takes two {@link (Multi)Polygon(s)} and returns a combined polygon. If the input polygons are not contiguous, this function returns a {@link MultiPolygon} feature.
  6. *
  7. * @name union
  8. * @param {Feature<Polygon|MultiPolygon>} polygon1 input Polygon feature
  9. * @param {Feature<Polygon|MultiPolygon>} polygon2 Polygon feature to difference from polygon1
  10. * @param {Object} [options={}] Optional Parameters
  11. * @param {Object} [options.properties={}] Translate Properties to output Feature
  12. * @returns {Feature<(Polygon|MultiPolygon)>} a combined {@link Polygon} or {@link MultiPolygon} feature, or null if the inputs are empty
  13. * @example
  14. * var poly1 = turf.polygon([[
  15. * [-82.574787, 35.594087],
  16. * [-82.574787, 35.615581],
  17. * [-82.545261, 35.615581],
  18. * [-82.545261, 35.594087],
  19. * [-82.574787, 35.594087]
  20. * ]], {"fill": "#0f0"});
  21. * var poly2 = turf.polygon([[
  22. * [-82.560024, 35.585153],
  23. * [-82.560024, 35.602602],
  24. * [-82.52964, 35.602602],
  25. * [-82.52964, 35.585153],
  26. * [-82.560024, 35.585153]
  27. * ]], {"fill": "#00f"});
  28. *
  29. * var union = turf.union(poly1, poly2);
  30. *
  31. * //addToMap
  32. * var addToMap = [poly1, poly2, union];
  33. */
  34. function union(poly1, poly2, options) {
  35. if (options === void 0) { options = {}; }
  36. var geom1 = getGeom(poly1);
  37. var geom2 = getGeom(poly2);
  38. var unioned = polygonClipping.union(geom1.coordinates, geom2.coordinates);
  39. if (unioned.length === 0)
  40. return null;
  41. if (unioned.length === 1)
  42. return polygon(unioned[0], options.properties);
  43. else
  44. return multiPolygon(unioned, options.properties);
  45. }
  46. export default union;