turf-polygon-dissolve.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import clone from "@turf/clone";
  2. import { geometryCollection } from "@turf/helpers";
  3. import { getType } from "@turf/invariant";
  4. import { flattenEach } from "@turf/meta";
  5. import { merge } from "topojson-client";
  6. import { topology } from "topojson-server";
  7. /**
  8. * Dissolves all overlapping (Multi)Polygon
  9. *
  10. * @param {FeatureCollection<Polygon|MultiPolygon>} geojson Polygons to dissolve
  11. * @param {Object} [options={}] Optional parameters
  12. * @param {boolean} [options.mutate=false] Prevent input mutation
  13. * @returns {Feature<Polygon|MultiPolygon>} Dissolved Polygons
  14. */
  15. export default function polygonDissolve(geojson, options) {
  16. if (options === void 0) { options = {}; }
  17. // Validation
  18. if (getType(geojson) !== "FeatureCollection") {
  19. throw new Error("geojson must be a FeatureCollection");
  20. }
  21. if (!geojson.features.length) {
  22. throw new Error("geojson is empty");
  23. }
  24. // Clone geojson to avoid side effects
  25. // Topojson modifies in place, so we need to deep clone first
  26. if (options.mutate === false || options.mutate === undefined) {
  27. geojson = clone(geojson);
  28. }
  29. var geoms = [];
  30. flattenEach(geojson, function (feature) {
  31. geoms.push(feature.geometry);
  32. });
  33. var topo = topology({ geoms: geometryCollection(geoms).geometry });
  34. var merged = merge(topo, topo.objects.geoms.geometries);
  35. return merged;
  36. }