index.js 2.4 KB

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