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

The following examples show how to use org.locationtech.jts.geom.Geometry#intersection() . 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: OmsGridsGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void createPoints( CoordinateReferenceSystem crs, GeometryFactory gf, List<LineString> verticals,
        List<LineString> horizontals ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POINT);
    b.setCRS(crs);
    b.add("the_geom", Point.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    Geometry gVer = gf.createMultiLineString(verticals.toArray(new LineString[0]));
    Geometry gHor = gf.createMultiLineString(horizontals.toArray(new LineString[0]));

    Geometry intersection = gHor.intersection(gVer);

    long index = 0;
    int numGeometries = intersection.getNumGeometries();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = intersection.getGeometryN(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 2
Source File: QueryIndexHelper.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Clip the provided bounded box with the statistics for the index
 */
public static Geometry clipIndexedBBOXConstraints(
    final SimpleFeatureType featureType,
    final Geometry bbox,
    final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> statsMap) {

  final String geoAttrName = featureType.getGeometryDescriptor().getLocalName();

  final StatisticsId statId =
      VectorStatisticsQueryBuilder.newBuilder().factory().bbox().fieldName(
          geoAttrName).build().getId();
  final BoundingBoxDataStatistics bboxStats = (BoundingBoxDataStatistics) statsMap.get(statId);
  if ((bboxStats != null) && bboxStats.isSet() && (bbox != null)) {
    final Geometry geo = new GeometryFactory().toGeometry(bboxStats.getResult());
    return geo.intersection(bbox);
  }
  return bbox;
}
 
Example 3
Source File: DBScanClusterList.java    From geowave with Apache License 2.0 6 votes vote down vote up
protected double interpolateFactor(final Geometry areaBeingMerged) {
  try {
    if (clusterGeo == null) {
      return 1.0;
    }
    final Geometry intersection = areaBeingMerged.intersection(clusterGeo);
    final double geo2Area = areaBeingMerged.getArea();
    if (intersection != null) {
      if ((intersection instanceof Point) && (areaBeingMerged instanceof Point)) {
        return 0.0;
      } else if (intersection.isEmpty()) {
        return 1.0;
      } else if (geo2Area > 0) {
        return 1.0 - (intersection.getArea() / geo2Area);
      } else {
        return 0.0;
      }
    }
    return 1.0;
  } catch (final Exception ex) {
    LOGGER.warn("Cannot calculate difference of geometries to interpolate size ", ex);
  }
  return 0.0;
}
 
Example 4
Source File: Shape.java    From MeteoInfo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get intersection shape
 * @param b Other shape
 * @return Intersection shape
 */
public Shape intersection(Shape b){
    Geometry g1 = this.toGeometry();
    Geometry g2 = b.toGeometry();
    Geometry g3 = g1.intersection(g2);
    return geometry2Shape(g3);
}
 
Example 5
Source File: RuleReaderServiceImpl.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
private Geometry intersect(List<RuleLimits> limits) {
    Geometry g = null;
    for (RuleLimits limit : limits) {
        Geometry area = limit.getAllowedArea();
        if(area != null) {
            if( g == null) {
                g = area;
            } else {
                g = g.intersection(area);
            }
        }
    }
    return g;
}
 
Example 6
Source File: RuleReaderServiceImpl.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
private Geometry intersect(Geometry g1, Geometry g2) {
    if(g1!=null) {
        if(g2==null)
            return g1;
        else
            return g1.intersection(g2);
    } else {
        return g2;
    }
}
 
Example 7
Source File: OmsVectorIntersector.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inMap1, inMap2);

    outMap = new DefaultFeatureCollection();

    if (!doKeepFirstAttributes) {
        SimpleFeatureCollection inMapTmp = inMap1;
        inMap1 = inMap2;
        inMap2 = inMapTmp;
    }

    List<Geometry> geometries = FeatureUtilities.featureCollectionToGeometriesList(inMap2, false, null);
    GeometryCollection geometryCollection = new GeometryCollection(geometries.toArray(new Geometry[geometries.size()]), gf);
    Geometry intersectionGeometry = geometryCollection.buffer(0);
    PreparedGeometry preparedIntersectionGeometry = PreparedGeometryFactory.prepare(intersectionGeometry);

    List<SimpleFeature> mainFeatures = FeatureUtilities.featureCollectionToList(inMap1);
    if (mainFeatures.size() == 0) {
        throw new ModelsIllegalargumentException("No features found in the layer.", this);
    }

    EGeometryType geometryType = EGeometryType.forGeometry((Geometry) mainFeatures.get(0).getDefaultGeometry());
    Class< ? > multiClazz = geometryType.getMultiClazz();
    EGeometryType newGeometryType = EGeometryType.forClass(multiClazz);
    FeatureGeometrySubstitutor sub = new FeatureGeometrySubstitutor(inMap1.getSchema(), multiClazz);

    pm.beginTask("Performing intersection...", mainFeatures.size());
    for( SimpleFeature feature : mainFeatures ) {
        Geometry geometry = (Geometry) feature.getDefaultGeometry();
        if (preparedIntersectionGeometry.intersects(geometry)) {
            Geometry intersection = geometry.intersection(intersectionGeometry);

            EGeometryType intersectionGeometryType = EGeometryType.forGeometry(intersection);
            if (intersectionGeometryType.isCompatibleWith(newGeometryType)) {
                SimpleFeature newFeature = sub.substituteGeometry(feature, intersection);
                ((DefaultFeatureCollection) outMap).add(newFeature);
            } else {
                pm.errorMessage("Could not add intersection result geometry to layer due to incompatibility: " + intersection);
            }
        }
        pm.worked(1);
    }
    pm.done();

}
 
Example 8
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 9
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});
      }
    }
  }