Source: simplify.js

  1. import { check } from "./helpers/check.js";
  2. import { topology } from "topojson-server";
  3. import { feature, quantize as quantiz } from "topojson-client";
  4. import { presimplify, quantile, simplify as simple } from "topojson-simplify";
  5. const topojson = Object.assign(
  6. {},
  7. { topology, presimplify, quantiz, quantile, simple, feature }
  8. );
  9. /**
  10. * @function simplify
  11. * @export
  12. * @summary Simplify geometries. The `simplify()` function allows to simplify a geometry using <code>topojson-simplify</code> library. The parameter k difine the The quantile of the simplification. By default, the generalization level is calculated automatically to ensure smooth map display.
  13. * @description Based on `topojson.simplify`.
  14. * @param {object|array} data - A GeoJSON FeatureCollection, an array of features, an array of geometries, a single feature or a single geometry.
  15. * @param {object} options - Optional parameters
  16. * @param {number} [options.k = undefined] - quantile of the simplification (from 0 to 1). If not defened, the generalization level is calculated automatically to ensure smooth map display.
  17. * @param {number} [options.quantize = undefined] - A smaller quantizeAmount produces a smaller file. Typical values are between 1e4 and 1e6, although it depends on the resolution you want in the output file.
  18. * @param {number} [options.arcs = 15000] - Instead of the k parameter, you can determine the level of generalization by targeting a specific number of arcs. The result will be an approximation.
  19. * @returns {object|array} - A GeoJSON FeatureCollection, an array of features, an array of geometries, a single feature or a single geometry (it depends on what you've set as `data`).
  20. * @example
  21. * geotoolbox.simplify(*a geojson*, {k: 0.1})
  22. */
  23. export function simplify(
  24. data,
  25. { k = undefined, quantize = undefined, arcs = 15000 } = {}
  26. ) {
  27. const handle = check(data);
  28. let x = handle.import(data);
  29. let topo = topojson.topology({ foo: x });
  30. let simpl = topojson.presimplify(topo);
  31. if (k == undefined) {
  32. k = arcs / simpl.arcs.flat().length;
  33. k = k > 1 ? 1 : k;
  34. }
  35. simpl = topojson.simple(simpl, topojson.quantile(simpl, k));
  36. if (quantize) {
  37. simpl = topojson.quantiz(simpl, quantize);
  38. }
  39. x.features = topojson.feature(simpl, Object.keys(simpl.objects)[0]).features;
  40. x.name = "simplify";
  41. return handle.export(x);
  42. }