index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict';
  2. var earcut = require('earcut');
  3. var helpers = require('@turf/helpers');
  4. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  5. var earcut__default = /*#__PURE__*/_interopDefaultLegacy(earcut);
  6. /**
  7. * Tesselates a {@link Feature<Polygon>} into a {@link FeatureCollection<Polygon>} of triangles
  8. * using [earcut](https://github.com/mapbox/earcut).
  9. *
  10. * @name tesselate
  11. * @param {Feature<Polygon>} poly the polygon to tesselate
  12. * @returns {FeatureCollection<Polygon>} a geometrycollection feature
  13. * @example
  14. * var poly = turf.polygon([[[11, 0], [22, 4], [31, 0], [31, 11], [21, 15], [11, 11], [11, 0]]]);
  15. * var triangles = turf.tesselate(poly);
  16. *
  17. * //addToMap
  18. * var addToMap = [poly, triangles]
  19. */
  20. function tesselate(poly) {
  21. if (
  22. !poly.geometry ||
  23. (poly.geometry.type !== "Polygon" && poly.geometry.type !== "MultiPolygon")
  24. ) {
  25. throw new Error("input must be a Polygon or MultiPolygon");
  26. }
  27. var fc = { type: "FeatureCollection", features: [] };
  28. if (poly.geometry.type === "Polygon") {
  29. fc.features = processPolygon(poly.geometry.coordinates);
  30. } else {
  31. poly.geometry.coordinates.forEach(function (coordinates) {
  32. fc.features = fc.features.concat(processPolygon(coordinates));
  33. });
  34. }
  35. return fc;
  36. }
  37. function processPolygon(coordinates) {
  38. var data = flattenCoords(coordinates);
  39. var dim = 2;
  40. var result = earcut__default['default'](data.vertices, data.holes, dim);
  41. var features = [];
  42. var vertices = [];
  43. result.forEach(function (vert, i) {
  44. var index = result[i];
  45. vertices.push([data.vertices[index * dim], data.vertices[index * dim + 1]]);
  46. });
  47. for (var i = 0; i < vertices.length; i += 3) {
  48. var coords = vertices.slice(i, i + 3);
  49. coords.push(vertices[i]);
  50. features.push(helpers.polygon([coords]));
  51. }
  52. return features;
  53. }
  54. function flattenCoords(data) {
  55. var dim = data[0][0].length,
  56. result = { vertices: [], holes: [], dimensions: dim },
  57. holeIndex = 0;
  58. for (var i = 0; i < data.length; i++) {
  59. for (var j = 0; j < data[i].length; j++) {
  60. for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
  61. }
  62. if (i > 0) {
  63. holeIndex += data[i - 1].length;
  64. result.holes.push(holeIndex);
  65. }
  66. }
  67. return result;
  68. }
  69. module.exports = tesselate;
  70. module.exports.default = tesselate;