index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // index.ts
  2. import { featureCollection, lineString } from "@turf/helpers";
  3. import { getCoords } from "@turf/invariant";
  4. import { flattenEach } from "@turf/meta";
  5. function lineSegment(geojson) {
  6. if (!geojson) {
  7. throw new Error("geojson is required");
  8. }
  9. const results = [];
  10. flattenEach(geojson, (feature) => {
  11. lineSegmentFeature(feature, results);
  12. });
  13. return featureCollection(results);
  14. }
  15. function lineSegmentFeature(geojson, results) {
  16. let coords = [];
  17. const geometry = geojson.geometry;
  18. if (geometry !== null) {
  19. switch (geometry.type) {
  20. case "Polygon":
  21. coords = getCoords(geometry);
  22. break;
  23. case "LineString":
  24. coords = [getCoords(geometry)];
  25. }
  26. coords.forEach((coord) => {
  27. const segments = createSegments(coord, geojson.properties);
  28. segments.forEach((segment) => {
  29. segment.id = results.length;
  30. results.push(segment);
  31. });
  32. });
  33. }
  34. }
  35. function createSegments(coords, properties) {
  36. const segments = [];
  37. coords.reduce((previousCoords, currentCoords) => {
  38. const segment = lineString([previousCoords, currentCoords], properties);
  39. segment.bbox = bbox(previousCoords, currentCoords);
  40. segments.push(segment);
  41. return currentCoords;
  42. });
  43. return segments;
  44. }
  45. function bbox(coords1, coords2) {
  46. const x1 = coords1[0];
  47. const y1 = coords1[1];
  48. const x2 = coords2[0];
  49. const y2 = coords2[1];
  50. const west = x1 < x2 ? x1 : x2;
  51. const south = y1 < y2 ? y1 : y2;
  52. const east = x1 > x2 ? x1 : x2;
  53. const north = y1 > y2 ? y1 : y2;
  54. return [west, south, east, north];
  55. }
  56. var turf_line_segment_default = lineSegment;
  57. export {
  58. turf_line_segment_default as default,
  59. lineSegment
  60. };
  61. //# sourceMappingURL=index.js.map