index.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. var helpers_1 = require("@turf/helpers");
  4. var invariant_1 = require("@turf/invariant");
  5. var lineclip_1 = require("./lib/lineclip");
  6. /**
  7. * Takes a {@link Feature} and a bbox and clips the feature to the bbox using
  8. * [lineclip](https://github.com/mapbox/lineclip).
  9. * May result in degenerate edges when clipping Polygons.
  10. *
  11. * @name bboxClip
  12. * @param {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} feature feature to clip to the bbox
  13. * @param {BBox} bbox extent in [minX, minY, maxX, maxY] order
  14. * @returns {Feature<LineString|MultiLineString|Polygon|MultiPolygon>} clipped Feature
  15. * @example
  16. * var bbox = [0, 0, 10, 10];
  17. * var poly = turf.polygon([[[2, 2], [8, 4], [12, 8], [3, 7], [2, 2]]]);
  18. *
  19. * var clipped = turf.bboxClip(poly, bbox);
  20. *
  21. * //addToMap
  22. * var addToMap = [bbox, poly, clipped]
  23. */
  24. function bboxClip(feature, bbox) {
  25. var geom = invariant_1.getGeom(feature);
  26. var type = geom.type;
  27. var properties = feature.type === "Feature" ? feature.properties : {};
  28. var coords = geom.coordinates;
  29. switch (type) {
  30. case "LineString":
  31. case "MultiLineString": {
  32. var lines_1 = [];
  33. if (type === "LineString") {
  34. coords = [coords];
  35. }
  36. coords.forEach(function (line) {
  37. lineclip_1.lineclip(line, bbox, lines_1);
  38. });
  39. if (lines_1.length === 1) {
  40. return helpers_1.lineString(lines_1[0], properties);
  41. }
  42. return helpers_1.multiLineString(lines_1, properties);
  43. }
  44. case "Polygon":
  45. return helpers_1.polygon(clipPolygon(coords, bbox), properties);
  46. case "MultiPolygon":
  47. return helpers_1.multiPolygon(coords.map(function (poly) {
  48. return clipPolygon(poly, bbox);
  49. }), properties);
  50. default:
  51. throw new Error("geometry " + type + " not supported");
  52. }
  53. }
  54. exports.default = bboxClip;
  55. function clipPolygon(rings, bbox) {
  56. var outRings = [];
  57. for (var _i = 0, rings_1 = rings; _i < rings_1.length; _i++) {
  58. var ring = rings_1[_i];
  59. var clipped = lineclip_1.polygonclip(ring, bbox);
  60. if (clipped.length > 0) {
  61. if (clipped[0][0] !== clipped[clipped.length - 1][0] ||
  62. clipped[0][1] !== clipped[clipped.length - 1][1]) {
  63. clipped.push(clipped[0]);
  64. }
  65. if (clipped.length >= 4) {
  66. outRings.push(clipped);
  67. }
  68. }
  69. }
  70. return outRings;
  71. }