index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // index.ts
  2. import earcut from "earcut";
  3. import { polygon } from "@turf/helpers";
  4. function tesselate(poly) {
  5. if (!poly.geometry || poly.geometry.type !== "Polygon" && poly.geometry.type !== "MultiPolygon") {
  6. throw new Error("input must be a Polygon or MultiPolygon");
  7. }
  8. const fc = {
  9. type: "FeatureCollection",
  10. features: []
  11. };
  12. if (poly.geometry.type === "Polygon") {
  13. fc.features = processPolygon(poly.geometry.coordinates);
  14. } else {
  15. poly.geometry.coordinates.forEach(function(coordinates) {
  16. fc.features = fc.features.concat(processPolygon(coordinates));
  17. });
  18. }
  19. return fc;
  20. }
  21. function processPolygon(coordinates) {
  22. const data = flattenCoords(coordinates);
  23. const dim = 2;
  24. const result = earcut(data.vertices, data.holes, dim);
  25. const features = [];
  26. const vertices = [];
  27. result.forEach(function(vert, i2) {
  28. const index = result[i2];
  29. vertices.push([data.vertices[index * dim], data.vertices[index * dim + 1]]);
  30. });
  31. for (var i = 0; i < vertices.length; i += 3) {
  32. const coords = vertices.slice(i, i + 3);
  33. coords.push(vertices[i]);
  34. features.push(polygon([coords]));
  35. }
  36. return features;
  37. }
  38. function flattenCoords(data) {
  39. const dim = data[0][0].length, result = {
  40. vertices: [],
  41. holes: [],
  42. dimensions: dim
  43. };
  44. let holeIndex = 0;
  45. for (let i = 0; i < data.length; i++) {
  46. for (let j = 0; j < data[i].length; j++) {
  47. for (let d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  48. }
  49. if (i > 0) {
  50. holeIndex += data[i - 1].length;
  51. result.holes.push(holeIndex);
  52. }
  53. }
  54. return result;
  55. }
  56. var turf_tesselate_default = tesselate;
  57. export {
  58. turf_tesselate_default as default,
  59. tesselate
  60. };
  61. //# sourceMappingURL=index.js.map