index.js 2.0 KB

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