index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { isObject, featureCollection, polygon } from '@turf/helpers';
  2. import { collectionOf } from '@turf/invariant';
  3. import { voronoi as voronoi$1 } from 'd3-voronoi';
  4. /**
  5. * @private
  6. * @param {Array<Array<number>>} coords representing a polygon
  7. * @returns {Feature<Polygon>} polygon
  8. */
  9. function coordsToPolygon(coords) {
  10. coords = coords.slice();
  11. coords.push(coords[0]);
  12. return polygon([coords]);
  13. }
  14. /**
  15. * Takes a FeatureCollection of points, and a bounding box, and returns a FeatureCollection
  16. * of Voronoi polygons.
  17. *
  18. * The Voronoi algorithim used comes from the d3-voronoi package.
  19. *
  20. * @name voronoi
  21. * @param {FeatureCollection<Point>} points to find the Voronoi polygons around.
  22. * @param {Object} [options={}] Optional parameters
  23. * @param {number[]} [options.bbox=[-180, -85, 180, -85]] clipping rectangle, in [minX, minY, maxX, MaxY] order.
  24. * @returns {FeatureCollection<Polygon>} a set of polygons, one per input point.
  25. * @example
  26. * var options = {
  27. * bbox: [-70, 40, -60, 60]
  28. * };
  29. * var points = turf.randomPoint(100, options);
  30. * var voronoiPolygons = turf.voronoi(points, options);
  31. *
  32. * //addToMap
  33. * var addToMap = [voronoiPolygons, points];
  34. */
  35. function voronoi(points, options) {
  36. // Optional params
  37. options = options || {};
  38. if (!isObject(options)) throw new Error("options is invalid");
  39. var bbox = options.bbox || [-180, -85, 180, 85];
  40. // Input Validation
  41. if (!points) throw new Error("points is required");
  42. if (!Array.isArray(bbox)) throw new Error("bbox is invalid");
  43. collectionOf(points, "Point", "points");
  44. // Main
  45. return featureCollection(
  46. voronoi$1()
  47. .x(function (feature) {
  48. return feature.geometry.coordinates[0];
  49. })
  50. .y(function (feature) {
  51. return feature.geometry.coordinates[1];
  52. })
  53. .extent([
  54. [bbox[0], bbox[1]],
  55. [bbox[2], bbox[3]],
  56. ])
  57. .polygons(points.features)
  58. .map(coordsToPolygon)
  59. );
  60. }
  61. export default voronoi;