Source: control/difference.js

  1. import OL3Parser from 'jsts/org/locationtech/jts/io/OL3Parser';
  2. import { OverlayOp } from 'jsts/org/locationtech/jts/operation/overlay';
  3. import LinearRing from 'ol/geom/LinearRing';
  4. import {
  5. Point,
  6. LineString,
  7. Polygon,
  8. MultiPoint,
  9. MultiLineString,
  10. MultiPolygon,
  11. } from 'ol/geom';
  12. import TopologyControl from './topology';
  13. import diffSVG from '../../img/difference.svg';
  14. /**
  15. * Control for creating a difference of geometries.
  16. * @extends {ole.Control}
  17. * @alias ole.Difference
  18. */
  19. class Difference extends TopologyControl {
  20. /**
  21. * @inheritdoc
  22. * @param {Object} [options] Control options.
  23. * @param {number} [options.hitTolerance] Select tolerance in pixels
  24. * (default is 10)
  25. */
  26. constructor(options) {
  27. super({
  28. title: 'Difference',
  29. className: 'ole-control-difference',
  30. image: diffSVG,
  31. ...options,
  32. });
  33. }
  34. /**
  35. * Apply a difference operation for given features.
  36. * @param {Array.<ol.Feature>} features Features.
  37. */
  38. applyTopologyOperation(features) {
  39. super.applyTopologyOperation(features);
  40. if (features.length < 2) {
  41. return;
  42. }
  43. const parser = new OL3Parser();
  44. parser.inject(
  45. Point,
  46. LineString,
  47. LinearRing,
  48. Polygon,
  49. MultiPoint,
  50. MultiLineString,
  51. MultiPolygon,
  52. );
  53. for (let i = 1; i < features.length; i += 1) {
  54. const geom = parser.read(features[0].getGeometry());
  55. const otherGeom = parser.read(features[i].getGeometry());
  56. const diffGeom = OverlayOp.difference(geom, otherGeom);
  57. features[0].setGeometry(parser.write(diffGeom));
  58. features[i].setGeometry(null);
  59. }
  60. }
  61. }
  62. export default Difference;