index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { featureCollection, lineString, multiLineString } from "@turf/helpers";
  2. import { getGeom } from "@turf/invariant";
  3. /**
  4. * Converts a {@link Polygon} to {@link LineString|(Multi)LineString} or {@link MultiPolygon} to a
  5. * {@link FeatureCollection} of {@link LineString|(Multi)LineString}.
  6. *
  7. * @name polygonToLine
  8. * @param {Feature<Polygon|MultiPolygon>} poly Feature to convert
  9. * @param {Object} [options={}] Optional parameters
  10. * @param {Object} [options.properties={}] translates GeoJSON properties to Feature
  11. * @returns {FeatureCollection|Feature<LineString|MultiLinestring>} converted (Multi)Polygon to (Multi)LineString
  12. * @example
  13. * var poly = turf.polygon([[[125, -30], [145, -30], [145, -20], [125, -20], [125, -30]]]);
  14. *
  15. * var line = turf.polygonToLine(poly);
  16. *
  17. * //addToMap
  18. * var addToMap = [line];
  19. */
  20. export default function (poly, options) {
  21. if (options === void 0) { options = {}; }
  22. var geom = getGeom(poly);
  23. if (!options.properties && poly.type === "Feature") {
  24. options.properties = poly.properties;
  25. }
  26. switch (geom.type) {
  27. case "Polygon":
  28. return polygonToLine(geom, options);
  29. case "MultiPolygon":
  30. return multiPolygonToLine(geom, options);
  31. default:
  32. throw new Error("invalid poly");
  33. }
  34. }
  35. /**
  36. * @private
  37. */
  38. export function polygonToLine(poly, options) {
  39. if (options === void 0) { options = {}; }
  40. var geom = getGeom(poly);
  41. var coords = geom.coordinates;
  42. var properties = options.properties
  43. ? options.properties
  44. : poly.type === "Feature"
  45. ? poly.properties
  46. : {};
  47. return coordsToLine(coords, properties);
  48. }
  49. /**
  50. * @private
  51. */
  52. export function multiPolygonToLine(multiPoly, options) {
  53. if (options === void 0) { options = {}; }
  54. var geom = getGeom(multiPoly);
  55. var coords = geom.coordinates;
  56. var properties = options.properties
  57. ? options.properties
  58. : multiPoly.type === "Feature"
  59. ? multiPoly.properties
  60. : {};
  61. var lines = [];
  62. coords.forEach(function (coord) {
  63. lines.push(coordsToLine(coord, properties));
  64. });
  65. return featureCollection(lines);
  66. }
  67. /**
  68. * @private
  69. */
  70. export function coordsToLine(coords, properties) {
  71. if (coords.length > 1) {
  72. return multiLineString(coords, properties);
  73. }
  74. return lineString(coords[0], properties);
  75. }