index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { polygon, multiPolygon } from '@turf/helpers';
  2. import polygonClipping from 'polygon-clipping';
  3. /**
  4. * Takes any type of {@link Polygon|polygon} and an optional mask and returns a {@link Polygon|polygon} exterior ring with holes.
  5. *
  6. * @name mask
  7. * @param {FeatureCollection|Feature<Polygon|MultiPolygon>} polygon GeoJSON Polygon used as interior rings or holes.
  8. * @param {Feature<Polygon>} [mask] GeoJSON Polygon used as the exterior ring (if undefined, the world extent is used)
  9. * @returns {Feature<Polygon>} Masked Polygon (exterior ring with holes).
  10. * @example
  11. * var polygon = turf.polygon([[[112, -21], [116, -36], [146, -39], [153, -24], [133, -10], [112, -21]]]);
  12. * var mask = turf.polygon([[[90, -55], [170, -55], [170, 10], [90, 10], [90, -55]]]);
  13. *
  14. * var masked = turf.mask(polygon, mask);
  15. *
  16. * //addToMap
  17. * var addToMap = [masked]
  18. */
  19. function mask(polygon, mask) {
  20. // Define mask
  21. var maskPolygon = createMask(mask);
  22. var polygonOuters = null;
  23. if (polygon.type === "FeatureCollection") polygonOuters = unionFc(polygon);
  24. else
  25. polygonOuters = createGeomFromPolygonClippingOutput(
  26. polygonClipping.union(polygon.geometry.coordinates)
  27. );
  28. polygonOuters.geometry.coordinates.forEach(function (contour) {
  29. maskPolygon.geometry.coordinates.push(contour[0]);
  30. });
  31. return maskPolygon;
  32. }
  33. function unionFc(fc) {
  34. var unioned =
  35. fc.features.length === 2
  36. ? polygonClipping.union(
  37. fc.features[0].geometry.coordinates,
  38. fc.features[1].geometry.coordinates
  39. )
  40. : polygonClipping.union.apply(
  41. polygonClipping,
  42. fc.features.map(function (f) {
  43. return f.geometry.coordinates;
  44. })
  45. );
  46. return createGeomFromPolygonClippingOutput(unioned);
  47. }
  48. function createGeomFromPolygonClippingOutput(unioned) {
  49. return multiPolygon(unioned);
  50. }
  51. /**
  52. * Create Mask Coordinates
  53. *
  54. * @private
  55. * @param {Feature<Polygon>} [mask] default to world if undefined
  56. * @returns {Feature<Polygon>} mask coordinate
  57. */
  58. function createMask(mask) {
  59. var world = [
  60. [
  61. [180, 90],
  62. [-180, 90],
  63. [-180, -90],
  64. [180, -90],
  65. [180, 90],
  66. ],
  67. ];
  68. var coordinates = (mask && mask.geometry.coordinates) || world;
  69. return polygon(coordinates);
  70. }
  71. export default mask;