How to use @turf/difference - 8 common examples

To help you get started, we’ve selected a few @turf/difference examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github uber / nebula.gl / modules / layers / src / layers / selection-layer.js View on Github external
const allX = mousePoints.map(mousePoint => mousePoint[0]);
    const allY = mousePoints.map(mousePoint => mousePoint[1]);
    const x = Math.min(...allX);
    const y = Math.min(...allY);
    const maxX = Math.max(...allX);
    const maxY = Math.max(...allY);

    // Use a polygon to hide the outside, because pickObjects()
    // does not support polygons
    const landPointsPoly = polygon(coordinates);
    const bigBuffer = turfBuffer(landPointsPoly, EXPANSION_KM);
    let bigPolygon;
    try {
      // turfDifference throws an exception if the polygon
      // intersects with itself (TODO: check if true in all versions)
      bigPolygon = turfDifference(bigBuffer, landPointsPoly);
    } catch (e) {
      // invalid selection polygon
      console.log('turfDifference() error', e); // eslint-disable-line
      return;
    }

    this.setState({
      pendingPolygonSelection: {
        bigPolygon
      }
    });

    const blockerId = `${this.props.id}-${LAYER_ID_BLOCKER}`;

    // HACK, find a better way
    setTimeout(() => {
github uber / nebula.gl / modules / layers / src / mode-handlers / mode-handler.js View on Github external
console.warn(
          'booleanOperation only supported for single Polygon or MultiPolygon selection'
        );
        return null;
      }

      const feature = {
        type: 'Feature',
        geometry
      };

      let updatedGeometry;
      if (modeConfig.booleanOperation === 'union') {
        updatedGeometry = turfUnion(selectedFeature, feature);
      } else if (modeConfig.booleanOperation === 'difference') {
        updatedGeometry = turfDifference(selectedFeature, feature);
      } else if (modeConfig.booleanOperation === 'intersection') {
        updatedGeometry = turfIntersect(selectedFeature, feature);
      } else {
        // eslint-disable-next-line no-console,no-undef
        console.warn(`Invalid booleanOperation ${modeConfig.booleanOperation}`);
        return null;
      }

      if (!updatedGeometry) {
        // eslint-disable-next-line no-console,no-undef
        console.warn('Canceling edit. Boolean operation erased entire polygon.');
        return null;
      }

      const featureIndex = this.getSelectedFeatureIndexes()[0];
github uber / nebula.gl / modules / edit-modes / src / lib / geojson-edit-mode.js View on Github external
console.warn(
          'booleanOperation only supported for single Polygon or MultiPolygon selection'
        );
        return null;
      }

      const feature = {
        type: 'Feature',
        geometry
      };

      let updatedGeometry;
      if (modeConfig.booleanOperation === 'union') {
        updatedGeometry = turfUnion(selectedFeature, feature);
      } else if (modeConfig.booleanOperation === 'difference') {
        updatedGeometry = turfDifference(selectedFeature, feature);
      } else if (modeConfig.booleanOperation === 'intersection') {
        updatedGeometry = turfIntersect(selectedFeature, feature);
      } else {
        // eslint-disable-next-line no-console,no-undef
        console.warn(`Invalid booleanOperation ${modeConfig.booleanOperation}`);
        return null;
      }

      if (!updatedGeometry) {
        // eslint-disable-next-line no-console,no-undef
        console.warn('Canceling edit. Boolean operation erased entire polygon.');
        return null;
      }

      const featureIndex = props.selectedIndexes[0];
github uber / nebula.gl / modules / layers / src / mode-handlers / split-polygon-handler.js View on Github external
splitPolygon() {
    const selectedGeometry = this.getSelectedGeometry();
    const tentativeFeature = this.getTentativeFeature();
    const featureIndex = this.getSelectedFeatureIndexes()[0];
    const modeConfig = this.getModeConfig() || {};

    // Default gap in between the polygon
    let { gap = 0.1, units = 'centimeters' } = modeConfig;
    if (gap === 0) {
      gap = 0.1;
      units = 'centimeters';
    }

    const buffer = turfBuffer(tentativeFeature, gap, { units });
    const updatedGeometry = turfDifference(selectedGeometry, buffer);
    this._setTentativeFeature(null);
    if (!updatedGeometry) {
      // eslint-disable-next-line no-console,no-undef
      console.warn('Canceling edit. Split Polygon erased');
      return null;
    }

    const { type, coordinates } = updatedGeometry.geometry;
    let updatedCoordinates = [];
    if (type === 'Polygon') {
      // Update the coordinates as per Multipolygon
      updatedCoordinates = coordinates.map(c => [c]);
    } else {
      // Handle Case when Multipolygon has holes
      updatedCoordinates = coordinates.reduce((agg, prev) => {
        prev.forEach(p => {
github geoman-io / leaflet-geoman / src / js / Draw / L.PM.Draw.Cut.js View on Github external
layers.forEach(l => {
      // find layer difference
      const diff = difference(l.toGeoJSON(15), layer.toGeoJSON(15));

      // the resulting layer after the cut
      const resultingLayer = L.geoJSON(diff, l.options).addTo(this._map);
      resultingLayer.addTo(this._map);

      // give the new layer the original options
      resultingLayer.pm.enable(this.options);
      resultingLayer.pm.disable();

      // fire pm:cut on the cutted layer
      l.fire('pm:cut', {
        shape: this._shape,
        layer: resultingLayer,
        originalLayer: l,
      });
github uber / nebula.gl / modules / main / src / lib / deck-renderer / deck-drawer.js View on Github external
data.push({
        polygon: this.landPoints,
        lineColor: POLYGON_LINE_COLOR,
        fillColor: POLYGON_FILL_COLOR
      });

      // Hack: use a polygon to hide the outside, because pickObjects()
      // does not support polygons
      if (this.landPoints.length >= 3) {
        const landPointsPoly = polygon([[...this.landPoints, this.landPoints[0]]]);
        const bigBuffer = turfBuffer(point(this.landPoints[0]), EXPANSION_KM);
        let bigPolygon;
        try {
          // turfDifference throws an exception if the polygon
          // intersects with itself
          bigPolygon = turfDifference(bigBuffer, landPointsPoly);
          dataPick.push({
            polygon: bigPolygon.geometry.coordinates,
            fillColor: [0, 0, 0, 1]
          });
          this.validPolygon = true;
        } catch (e) {
          // invalid selection polygon
          this.validPolygon = false;
        }
      }
    }

    if (this.landPoints.length) {
      // highlight start point
      data.push({
        polygon: this._makeStartPointHighlight(this.landPoints[0]),
github terrestris / ol-util / src / GeometryUtil / GeometryUtil.js View on Github external
toCut.forEach((tocutPart, i) => {
                let intersection = difference(tocutPart, holes);
                if (intersection && (intersection.geometry.type === 'Polygon' || intersection.geometry.type === 'MultiPolygon')) {
                  if (intersection.geometry.type === 'MultiPolygon') {
                    intersection.geometry.coordinates.forEach(intersectPolyCoords => {
                      polygonWithoutHoles.push(makePolygon(intersectPolyCoords));
                    });
                  } else {
                    polygonWithoutHoles[i] = intersection;
                  }
                }
              });
            });
github terrestris / ol-util / src / GeometryUtil / GeometryUtil.js View on Github external
static difference(polygon1, polygon2, projection = 'EPSG:3857') {
    const geoJsonFormat = new OlFormatGeoJSON({
      dataProjection: 'EPSG:4326',
      featureProjection: projection
    });
    const feat1 = polygon1 instanceof OlFeature ? polygon1
      : new OlFeature({
        geometry: polygon1
      });
    const feat2 = polygon2 instanceof OlFeature ? polygon2
      : new OlFeature({
        geometry: polygon2
      });
    const geojson1 = geoJsonFormat.writeFeatureObject(feat1);
    const geojson2 = geoJsonFormat.writeFeatureObject(feat2);
    const intersection = difference(geojson1, geojson2);
    const feature = geoJsonFormat.readFeature(intersection);
    if (polygon1 instanceof OlFeature && polygon2 instanceof OlFeature) {
      return feature;
    } else {
      return feature.getGeometry();
    }
  }

@turf/difference

turf difference module

MIT
Latest version published 4 months ago

Package Health Score

94 / 100
Full package analysis

Popular @turf/difference functions