Java Code Examples for org.locationtech.jts.geom.Geometry#intersects()

The following examples show how to use org.locationtech.jts.geom.Geometry#intersects() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 6 votes vote down vote up
protected static Geometry findIntersectedGeoms(Geometry srcGeom, List<Geometry> geometries) {
    List<Geometry> intersected = new ArrayList<>();
    
    // find all geometries which intersect with with srcGeom
    Iterator<Geometry> geomIter = geometries.iterator();
    while (geomIter.hasNext()) {
        Geometry geom = geomIter.next();
        if (geom.intersects(srcGeom)) {
            geomIter.remove();
            intersected.add(geom);
        }
    }
    
    // compute the envelope for the intersected geometries and the source geometry, and look for more intersections
    if (!intersected.isEmpty()) {
        intersected.add(srcGeom);
        Geometry mergedGeom = new GeometryCollection(intersected.toArray(new Geometry[intersected.size()]), new GeometryFactory()).getEnvelope();
        return findIntersectedGeoms(mergedGeom, geometries);
    }
    
    return srcGeom;
}
 
Example 2
Source File: VectorTileEncoder.java    From java-vector-tile with Apache License 2.0 6 votes vote down vote up
/**
 * Clip geometry according to buffer given at construct time. This method
 * can be overridden to change clipping behavior. See also
 * {@link #clipCovers(Geometry)}.
 *
 * @param geometry
 * @return
 */
protected Geometry clipGeometry(Geometry geometry) {
    try {
        Geometry original = geometry;
        geometry = clipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(clipGeometry)) {
            Geometry originalViaWkt = new WKTReader().read(original.toText());
            geometry = clipGeometry.intersection(originalViaWkt);
        }

        return geometry;
    } catch (TopologyException e) {
        // could not intersect. original geometry will be used instead.
        return geometry;
    } catch (ParseException e1) {
        // could not encode/decode WKT. original geometry will be used
        // instead.
        return geometry;
    }
}
 
Example 3
Source File: GeoWaveFunctions.java    From datawave with Apache License 2.0 5 votes vote down vote up
/**
 * Test intersection of a set of geometry with a field value
 */
private static boolean intersectsGeometries(Object fieldValue, Geometry[] geometries) {
    Geometry thisGeom = getGeometryFromFieldValue(fieldValue);
    for (Geometry g : geometries) {
        if (thisGeom.intersects(g)) {
            return true;
        }
    }
    return false;
}
 
Example 4
Source File: NoDataMetadataFactory.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isNoData(final int x, final int y) {
  if (!acceptNone) {
    for (final Geometry shape : shapes) {
      // if any one intersects the point than it is not "no data"
      // based on shape
      if (shape.intersects(new GeometryFactory().createPoint(new Coordinate(x, y)))) {
        return false;
      }
    }
    return true;
  }
  return false;
}
 
Example 5
Source File: GeometryHullTool.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Forms create edges between two shapes maintaining convexity.
 *
 * <p> Does not currently work if the shapes intersect
 */
public Geometry connect(final Geometry shape1, final Geometry shape2) {

  try {
    if ((shape1 instanceof Polygon)
        && (shape2 instanceof Polygon)
        && !shape1.intersects(shape2)) {
      return connect(shape1, shape2, getClosestPoints(shape1, shape2, distanceFnForCoordinate));
    }
    return UnaryUnionOp.union(Arrays.asList(shape1, shape2));
  } catch (final Exception ex) {
    LOGGER.warn("Exception caught in connect method", ex);
  }
  return createHullFromGeometry(shape1, Arrays.asList(shape2.getCoordinates()), false);
}
 
Example 6
Source File: Shape.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * If this shape intersects another one
 * @param other Other shape
 * @return Intersects or not
 */
public boolean intersects(Shape other){
    Geometry g1 = this.toGeometry();
    Geometry g2 = other.toGeometry();
    return g1.intersects(g2);
}
 
Example 7
Source File: GeoWaveFunctions.java    From datawave with Apache License 2.0 4 votes vote down vote up
public static boolean intersects(Object fieldValue, String geoString) {
    Geometry otherGeom = AbstractGeometryNormalizer.parseGeometry(geoString);
    Geometry thisGeom = getGeometryFromFieldValue(fieldValue);
    return thisGeom.intersects(otherGeom);
}
 
Example 8
Source File: OmsHoughCirclesRasterCleaner.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Execute
public void process() throws Exception {
    checkNull(inVector, pMaxOverlap, inRaster);

    RandomIter rasterIter = CoverageUtilities.getRandomIterator(inRaster);
    GridGeometry2D gridGeometry = inRaster.getGridGeometry();
    double[] tm_utm_tac = new double[3];

    STRtree circlesTree = FeatureUtilities.featureCollectionToSTRtree(inVector);
    List<SimpleFeature> circlesList = FeatureUtilities.featureCollectionToList(inVector);

    DefaultFeatureCollection outFC = new DefaultFeatureCollection();

    for( SimpleFeature circleFeature : circlesList ) {
        Geometry geometry = (Geometry) circleFeature.getDefaultGeometry();
        Polygon circle = (Polygon) geometry.getGeometryN(0);
        PreparedGeometry preparedCircle = PreparedGeometryFactory.prepare(circle);

        List<SimpleFeature> circlesAround = circlesTree.query(circle.getEnvelopeInternal());
        List<Geometry> intersectedCircles = new ArrayList<Geometry>();
        for( SimpleFeature circleAround : circlesAround ) {
            if (circleAround.equals(circleFeature)) {
                continue;
            }
            Geometry circleAroundGeometry = (Geometry) circleAround.getDefaultGeometry();
            if (preparedCircle.intersects(circleAroundGeometry)) {
                intersectedCircles.add(circleAroundGeometry);
            }
        }

        Point centroid = circle.getCentroid();
        int intersectionsCount = intersectedCircles.size();
        if (intersectionsCount != 0) {
            // check how many circles overlapped
            if (intersectionsCount > pMaxOverlapCount) {
                continue;
            }
            // check if the circles overlap too much, i.e. cover their baricenter
            boolean intersected = false;
            for( Geometry intersectedCircle : intersectedCircles ) {
                if (intersectedCircle.intersects(centroid)) {
                    intersected = true;
                    break;
                }
            }
            if (intersected) {
                continue;
            }
        }
        // check if the center has a raster value, i.e. is not empty
        double value = CoverageUtilities.getValue(inRaster, centroid.getCoordinate());
        if (!HMConstants.isNovalue(value)) {
            continue;
        }

        // check if the inner part of the circle is indeed rather empty

        // min, max, mean, var, sdev, activeCellCount, passiveCellCount
        double[] stats = OmsZonalStats.polygonStats(circle, gridGeometry, rasterIter, false, tm_utm_tac, 0, pm);
        // if we have many more active cells than passive cells, that is not a circle
        double activeCells = stats[5];
        double novalues = stats[6];
        if (activeCells * 1.5 > novalues) {
            continue;
        }

        // take it as valid circle
        outFC.add(circleFeature);
    }
    outCircles = outFC;

    rasterIter.done();
}
 
Example 9
Source File: GrassLegacyUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Fill polygon areas mapping on a raster
 * 
 * @param active the active region
 * @param polygon the jts polygon geometry
 * @param raster the empty raster data to be filled
 * @param rasterToMap the map from which the values to fill raster are taken (if null, the value
 *        parameter is used)
 * @param value the value to set if a second map is not given
 * @param monitor
 */
public static void rasterizePolygonGeometry( Window active, Geometry polygon, RasterData raster, RasterData rasterToMap,
        double value, IHMProgressMonitor monitor ) {
    GeometryFactory gFactory = new GeometryFactory();
    int rows = active.getRows();
    int cols = active.getCols();
    double delta = active.getWEResolution() / 4.0;

    monitor.beginTask("rasterizing...", rows); //$NON-NLS-1$
    for( int i = 0; i < rows; i++ ) {
        monitor.worked(1);
        // do scan line to fill the polygon
        Coordinate west = rowColToCenterCoordinates(active, i, 0);
        Coordinate east = rowColToCenterCoordinates(active, i, cols - 1);
        LineString line = gFactory.createLineString(new Coordinate[]{west, east});
        if (polygon.intersects(line)) {
            Geometry internalLines = polygon.intersection(line);
            Coordinate[] coords = internalLines.getCoordinates();
            for( int j = 0; j < coords.length; j = j + 2 ) {
                Coordinate startC = new Coordinate(coords[j].x + delta, coords[j].y);
                Coordinate endC = new Coordinate(coords[j + 1].x - delta, coords[j + 1].y);
                int[] startcol = coordinateToNearestRowCol(active, startC);
                int[] endcol = coordinateToNearestRowCol(active, endC);

                if (startcol == null || endcol == null) {
                    // vertex is outside of the region, ignore it
                    continue;
                }
                /*
                 * the part in between has to be filled
                 */
                for( int k = startcol[1]; k <= endcol[1]; k++ ) {
                    if (rasterToMap != null) {
                        raster.setValueAt(i, k, rasterToMap.getValueAt(i, k));
                    } else {
                        raster.setValueAt(i, k, value);
                    }
                }
            }

        }
    }
}
 
Example 10
Source File: LasTriangulation2Dsm.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void makeRow( STRtree tree, int newRows, GridGeometry2D newGridGeometry2D, WritableRaster newWR, int c )
        throws TransformException {
    for( int r = 0; r < newRows; r++ ) {
        DirectPosition worldPosition = newGridGeometry2D.gridToWorld(new GridCoordinates2D(c, r));
        double[] wpCoords = worldPosition.getCoordinate();
        Coordinate coordinate = new Coordinate(wpCoords[0], wpCoords[1]);
        Point point = gf.createPoint(coordinate);
        Envelope e = new Envelope(coordinate);
        List interceptedTriangles = tree.query(e);
        if (interceptedTriangles.size() == 0) {
            continue;
        }
        double newElev = -9999.0;
        for( Object object : interceptedTriangles ) {
            if (object instanceof Geometry) {
                Geometry triangle = (Geometry) object;
                if (!triangle.intersects(point)) {
                    continue;
                }
                Coordinate[] triangleCoords = triangle.getCoordinates();
                Coordinate c1 = new Coordinate(coordinate.x, coordinate.y, 1E4);
                Coordinate c2 = new Coordinate(coordinate.x, coordinate.y, -1E4);
                Coordinate intersection = GeometryUtilities.getLineWithPlaneIntersection(c1, c2, triangleCoords[0],
                        triangleCoords[1], triangleCoords[2]);
                double maxZ = max(triangleCoords[0].z, triangleCoords[1].z);
                maxZ = max(maxZ, triangleCoords[2].z);
                if (intersection.z > maxZ) {
                    boolean equals = NumericsUtilities.dEq(intersection.z, maxZ, 0.0001);
                    if (!equals) {
                        pm.errorMessage(triangle.toText());
                        pm.errorMessage(gf.createPoint(intersection).toText());
                        throw new RuntimeException("Intersection can't be  > than the triangle.");
                    }
                }
                if (intersection.z > newElev) {
                    newElev = intersection.z;
                }
            }
        }
        synchronized (newWR) {
            newWR.setSample(c, r, 0, newElev);
        }
    }
}
 
Example 11
Source File: GeometryHullToolTest.java    From geowave with Apache License 2.0 4 votes vote down vote up
public void testRandomConnect() throws IOException {

    final GeometryHullTool cg = new GeometryHullTool();
    cg.setDistanceFnForCoordinate(new CoordinateCircleDistanceFn());
    final Iterator<Geometry> it1 =
        GeometryGenerator.generate(1000, Arrays.asList(1.0), new DistortationFn() {
          final Random r = new Random(7777);

          @Override
          public double distort() {
            return 0.5 + (0.5 * r.nextDouble());
          }
        }, 5, new Envelope(45, 55, 35, 45));
    final Iterator<Geometry> it2 =
        GeometryGenerator.generate(1000, Arrays.asList(1.0), new DistortationFn() {
          final Random r = new Random(7777);

          @Override
          public double distort() {
            return 0.5 + (0.5 * r.nextDouble());
          }
        }, 5, new Envelope(30, 47, 20, 37));

    while (it1.hasNext()) {
      Geometry rightShape = it1.next();
      Geometry leftShape = it2.next();

      if (rightShape.intersects(leftShape)) {
        final Geometry inter = rightShape.intersection(leftShape);
        rightShape = rightShape.difference(inter);
        leftShape = leftShape.difference(inter);
      }

      ShapefileTool.writeShape(
          "test_random",
          new File("./target/test_randoms"),
          new Geometry[] {leftShape, rightShape});
      Geometry geo = cg.connect(leftShape, rightShape);

      ShapefileTool.writeShape(
          "test_random",
          new File("./target/test_random"),
          new Geometry[] {geo});
      if (!geo.isSimple()) {

        // assertTrue(false);
        geo = cg.connect(leftShape, rightShape);
        ShapefileTool.writeShape(
            "test_random2",
            new File("./target/test_random2"),
            new Geometry[] {geo});
      }
    }
  }
 
Example 12
Source File: GeomIntersects.java    From geowave with Apache License 2.0 4 votes vote down vote up
@Override
public boolean apply(final Geometry geom1, final Geometry geom2) {
  return geom1.intersects(geom2);
}