index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { isObject, multiPolygon, featureCollection } from '@turf/helpers';
  2. import { collectionOf } from '@turf/invariant';
  3. import { featureEach } from '@turf/meta';
  4. import flatten from '@turf/flatten';
  5. import polygonClipping from 'polygon-clipping';
  6. /**
  7. * Dissolves a FeatureCollection of {@link polygon} features, filtered by an optional property name:value.
  8. * Note that {@link mulitpolygon} features within the collection are not supported
  9. *
  10. * @name dissolve
  11. * @param {FeatureCollection<Polygon>} featureCollection input feature collection to be dissolved
  12. * @param {Object} [options={}] Optional parameters
  13. * @param {string} [options.propertyName] features with the same `propertyName` value will be dissolved.
  14. * @returns {FeatureCollection<Polygon>} a FeatureCollection containing the dissolved polygons
  15. * @example
  16. * var features = turf.featureCollection([
  17. * turf.polygon([[[0, 0], [0, 1], [1, 1], [1, 0], [0, 0]]], {combine: 'yes'}),
  18. * turf.polygon([[[0, -1], [0, 0], [1, 0], [1, -1], [0,-1]]], {combine: 'yes'}),
  19. * turf.polygon([[[1,-1],[1, 0], [2, 0], [2, -1], [1, -1]]], {combine: 'no'}),
  20. * ]);
  21. *
  22. * var dissolved = turf.dissolve(features, {propertyName: 'combine'});
  23. *
  24. * //addToMap
  25. * var addToMap = [features, dissolved]
  26. */
  27. function dissolve(fc, options) {
  28. // Optional parameters
  29. options = options || {};
  30. if (!isObject(options)) throw new Error("options is invalid");
  31. var propertyName = options.propertyName;
  32. // Input validation
  33. collectionOf(fc, "Polygon", "dissolve");
  34. // Main
  35. var outFeatures = [];
  36. if (!options.propertyName) {
  37. return flatten(
  38. multiPolygon(
  39. polygonClipping.union.apply(
  40. null,
  41. fc.features.map(function (f) {
  42. return f.geometry.coordinates;
  43. })
  44. )
  45. )
  46. );
  47. } else {
  48. var uniquePropertyVals = {};
  49. featureEach(fc, function (feature) {
  50. if (
  51. !Object.prototype.hasOwnProperty.call(
  52. uniquePropertyVals,
  53. feature.properties[propertyName]
  54. )
  55. ) {
  56. uniquePropertyVals[feature.properties[propertyName]] = [];
  57. }
  58. uniquePropertyVals[feature.properties[propertyName]].push(feature);
  59. });
  60. var vals = Object.keys(uniquePropertyVals);
  61. for (var i = 0; i < vals.length; i++) {
  62. var mp = multiPolygon(
  63. polygonClipping.union.apply(
  64. null,
  65. uniquePropertyVals[vals[i]].map(function (f) {
  66. return f.geometry.coordinates;
  67. })
  68. )
  69. );
  70. mp.properties[propertyName] = vals[i];
  71. outFeatures.push(mp);
  72. }
  73. }
  74. return flatten(featureCollection(outFeatures));
  75. }
  76. export default dissolve;