index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { polygon, } from "@turf/helpers";
  2. import { coordEach } from "@turf/meta";
  3. import concaveman from "concaveman";
  4. /**
  5. * Takes a {@link Feature} or a {@link FeatureCollection} and returns a convex hull {@link Polygon}.
  6. *
  7. * Internally this uses
  8. * the [convex-hull](https://github.com/mikolalysenko/convex-hull) module that implements a
  9. * [monotone chain hull](http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain).
  10. *
  11. * @name convex
  12. * @param {GeoJSON} geojson input Feature or FeatureCollection
  13. * @param {Object} [options={}] Optional parameters
  14. * @param {number} [options.concavity=Infinity] 1 - thin shape. Infinity - convex hull.
  15. * @param {Object} [options.properties={}] Translate Properties to Feature
  16. * @returns {Feature<Polygon>} a convex hull
  17. * @example
  18. * var points = turf.featureCollection([
  19. * turf.point([10.195312, 43.755225]),
  20. * turf.point([10.404052, 43.8424511]),
  21. * turf.point([10.579833, 43.659924]),
  22. * turf.point([10.360107, 43.516688]),
  23. * turf.point([10.14038, 43.588348]),
  24. * turf.point([10.195312, 43.755225])
  25. * ]);
  26. *
  27. * var hull = turf.convex(points);
  28. *
  29. * //addToMap
  30. * var addToMap = [points, hull]
  31. */
  32. export default function convex(geojson, options) {
  33. if (options === void 0) { options = {}; }
  34. // Default parameters
  35. options.concavity = options.concavity || Infinity;
  36. // Container
  37. var points = [];
  38. // Convert all points to flat 2D coordinate Array
  39. coordEach(geojson, function (coord) {
  40. points.push([coord[0], coord[1]]);
  41. });
  42. if (!points.length) {
  43. return null;
  44. }
  45. var convexHull = concaveman(points, options.concavity);
  46. // Convex hull should have at least 3 different vertices in order to create a valid polygon
  47. if (convexHull.length > 3) {
  48. return polygon([convexHull]);
  49. }
  50. return null;
  51. }