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

The following examples show how to use org.locationtech.jts.geom.Geometry#getEnvelopeInternal() . 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: JTS.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Finds an operation between the given CRS valid in the given area of interest.
 * This method does not verify the CRS of the given geometry.
 *
 * @param  sourceCRS       the CRS of source coordinates.
 * @param  targetCRS       the CRS of target coordinates.
 * @param  areaOfInterest  the area of interest.
 * @return the mathematical operation from {@code sourceCRS} to {@code targetCRS}.
 * @throws FactoryException if the operation can not be created.
 */
private static CoordinateOperation findOperation(final CoordinateReferenceSystem sourceCRS,
                                                 final CoordinateReferenceSystem targetCRS,
                                                 final Geometry areaOfInterest)
        throws FactoryException
{
    DefaultGeographicBoundingBox bbox = new DefaultGeographicBoundingBox();
    try {
        final Envelope e = areaOfInterest.getEnvelopeInternal();
        bbox.setBounds(new Envelope2D(sourceCRS, e.getMinX(), e.getMinY(), e.getWidth(), e.getHeight()));
    } catch (TransformException ex) {
        bbox = null;
        Logging.ignorableException(Logging.getLogger(Loggers.GEOMETRY), JTS.class, "transform", ex);
    }
    return CRS.findOperation(sourceCRS, targetCRS, bbox);
}
 
Example 2
Source File: FeatureBoundingBoxStatistics.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Override
protected Envelope getEnvelope(final SimpleFeature entry) {
  // incorporate the bounding box of the entry's envelope
  final Object o;
  if ((reprojectedType != null)
      && (transform != null)
      && !reprojectedType.getCoordinateReferenceSystem().equals(
          entry.getType().getCoordinateReferenceSystem())) {
    o =
        GeometryUtils.crsTransform(entry, reprojectedType, transform).getAttribute(
            getFieldName());
  } else {
    o = entry.getAttribute(getFieldName());
  }
  if ((o != null) && (o instanceof Geometry)) {
    final Geometry geometry = (Geometry) o;
    if (!geometry.isEmpty()) {
      return geometry.getEnvelopeInternal();
    }
  }
  return null;
}
 
Example 3
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * Recursively decompose geometry into a set of envelopes to create a single set.
 *
 * @param geometry
 * @param destinationListOfSets
 * @param checkTopoEquality
 */
private static boolean constructListOfConstraintSetsFromGeometry(
    final Geometry geometry,
    final List<ConstraintSet> destinationListOfSets,
    final boolean checkTopoEquality) {

  // Get the envelope of the geometry being held
  final int n = geometry.getNumGeometries();
  boolean retVal = true;
  if (n > 1) {
    retVal = false;
    for (int gi = 0; gi < n; gi++) {
      constructListOfConstraintSetsFromGeometry(
          geometry.getGeometryN(gi),
          destinationListOfSets,
          checkTopoEquality);
    }
  } else {
    final Envelope env = geometry.getEnvelopeInternal();
    destinationListOfSets.add(basicConstraintSetFromEnvelope(env));
    if (checkTopoEquality) {
      retVal = new GeometryFactory().toGeometry(env).equalsTopo(geometry);
    }
  }
  return retVal;
}
 
Example 4
Source File: PostgisDb.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getSpatialindexGeometryWherePiece( String tableName, String alias, Geometry geometry ) throws Exception {
    GeometryColumn gCol = getGeometryColumnsForTable(tableName);
    if (alias == null) {
        alias = "";
    } else {
        alias = alias + ".";
    }
    int srid = geometry.getSRID();
    Envelope envelopeInternal = geometry.getEnvelopeInternal();
    Polygon bounds = DbsUtilities.createPolygonFromEnvelope(envelopeInternal);
    String sql = alias + gCol.geometryColumnName + " && ST_GeomFromText('" + bounds.toText() + "'," + srid
            + ") AND ST_Intersects(" + alias + gCol.geometryColumnName + ",ST_GeomFromText('" + geometry.toText() + "',"
            + srid + "))";
    return sql;
}
 
Example 5
Source File: SpatialiteCommonMethods.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static String getSpatialindexGeometryWherePiece( ASpatialDb db, String tableName, String alias, Geometry geometry )
        throws Exception {
    String rowid = "";
    if (alias == null) {
        alias = "";
        rowid = tableName + ".ROWID";
    } else {
        rowid = alias + ".ROWID";
        alias = alias + ".";
    }

    Envelope envelope = geometry.getEnvelopeInternal();
    double x1 = envelope.getMinX();
    double x2 = envelope.getMaxX();
    double y1 = envelope.getMinY();
    double y2 = envelope.getMaxY();
    GeometryColumn gCol = db.getGeometryColumnsForTable(tableName);
    if (tableName.indexOf('.') != -1) {
        // if the tablename contains a dot, then it comes from an attached
        // database
        tableName = "DB=" + tableName;
    }
    String sql = "ST_Intersects(" + alias + gCol.geometryColumnName + ", " + "ST_GeomFromText('" + geometry.toText() + "')"
            + ") = 1 AND " + rowid + " IN ( SELECT ROWID FROM SpatialIndex WHERE "//
            + "f_table_name = '" + tableName + "' AND " //
            + "search_frame = BuildMbr(" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + "))";
    return sql;
}
 
Example 6
Source File: VectorBoundingBoxAggregation.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
protected Envelope getEnvelope(final SimpleFeature entry) {
  Object o;
  if ((fieldNameParam != null) && !fieldNameParam.isEmpty()) {
    o = entry.getAttribute(fieldNameParam.getFieldName());
  } else {
    o = entry.getDefaultGeometry();
  }
  if ((o != null) && (o instanceof Geometry)) {
    final Geometry geometry = (Geometry) o;
    return geometry.getEnvelopeInternal();
  }
  return null;
}
 
Example 7
Source File: GeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a latitude range from a JTS geometry
 *
 * @param geometry The JTS geometry
 * @return The y range
 */
public static NumericData yRangeFromGeometry(final Geometry geometry) {
  if ((geometry == null) || geometry.isEmpty()) {
    return new NumericRange(0, 0);
  }
  // Get the envelope of the geometry being held
  final Envelope env = geometry.getEnvelopeInternal();

  // Create a NumericRange object using the y axis
  return new NumericRange(env.getMinY(), env.getMaxY());
}
 
Example 8
Source File: AccumuloDataStoreStatsTest.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
protected Envelope getEnvelope(final TestGeometry entry) {
  // incorporate the bounding box of the entry's envelope
  final Geometry geometry = entry.geom;
  if ((geometry != null) && !geometry.isEmpty()) {
    return geometry.getEnvelopeInternal();
  }
  return null;
}
 
Example 9
Source File: H2GisDb.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getSpatialindexGeometryWherePiece( String tableName, String alias, Geometry geometry ) throws Exception {
    GeometryColumn gCol = getGeometryColumnsForTable(tableName);
    if (alias == null) {
        alias = "";
    } else {
        alias = alias + ".";
    }

    Envelope envelopeInternal = geometry.getEnvelopeInternal();
    Polygon bounds = DbsUtilities.createPolygonFromEnvelope(envelopeInternal);
    String sql = alias + gCol.geometryColumnName + " && ST_GeomFromText('" + bounds.toText() + "') AND ST_Intersects(" + alias
            + gCol.geometryColumnName + ",ST_GeomFromText('" + geometry.toText() + "'))";
    return sql;
}
 
Example 10
Source File: JtsGeometrySerde.java    From presto with Apache License 2.0 5 votes vote down vote up
private static void writeEnvelope(Geometry geometry, SliceOutput output)
{
    if (geometry.isEmpty()) {
        for (int i = 0; i < 4; i++) {
            output.writeDouble(NaN);
        }
        return;
    }

    Envelope envelope = geometry.getEnvelopeInternal();
    output.writeDouble(envelope.getMinX());
    output.writeDouble(envelope.getMinY());
    output.writeDouble(envelope.getMaxX());
    output.writeDouble(envelope.getMaxY());
}
 
Example 11
Source File: GeopackageTableLayer.java    From geopaparazzi with GNU General Public License v3.0 5 votes vote down vote up
private void updateGeometry(ASpatialDb db, String tableName, long id, Geometry geometry) throws Exception {
    int epsg = 4326;
    String pk = ((GPGeopackageDb) db).getPrimaryKey(tableName);

    IGeometryParser gp = db.getType().getGeometryParser();
    geometry.setSRID(epsg);
    Object obj = gp.toSqlObject(geometry);
    if (obj instanceof byte[]) {
        byte[] objBytes = (byte[]) obj;
        GeometryColumn gc = db.getGeometryColumnsForTable(tableName);
        String sql = "update " + tableName + " set " + gc.geometryColumnName + "=? where " + pk + "=" + id;

        db.execOnConnection(connection -> {
            try (IHMPreparedStatement pStmt = connection.prepareStatement(sql)) {
                pStmt.setBytes(1, objBytes);
                pStmt.executeUpdate();
            }
            return null;
        });

        Envelope env = geometry.getEnvelopeInternal();
        double minX = env.getMinX();
        double maxX = env.getMaxX();
        double minY = env.getMinY();
        double maxY = env.getMaxY();

        try {
            // also update rtree index, since it is not supported
            String sqlTree = "INSERT OR REPLACE INTO rtree_" + tableName + "_" + gc.geometryColumnName +
                    " VALUES (" + id + "," + minX + ", " + maxX + "," + minY + ", " + maxY + ");";
            db.executeInsertUpdateDeleteSql(sqlTree);
        } catch (Exception e) {
            GPLog.error(this, "ERROR on rtree", e);
        }

    } else {
        throw new IllegalArgumentException("Geometry object is not byte array.");
    }
}
 
Example 12
Source File: GridH2SpatialIndex.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param row Row.
 * @param rowId Row id.
 * @return Envelope.
 */
private SpatialKey getEnvelope(SearchRow row, long rowId) {
    Value v = row.getValue(columnIds[0]);
    Geometry g = ((ValueGeometry) v.convertTo(Value.GEOMETRY)).getGeometry();
    Envelope env = g.getEnvelopeInternal();
    return new SpatialKey(rowId,
        (float) env.getMinX(), (float) env.getMaxX(),
        (float) env.getMinY(), (float) env.getMaxY());
}
 
Example 13
Source File: SpatialiteWKBWriter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Writes a {@link Geometry} to an {@link OutStream}.
 *
 * @param geom the geometry to write
 * @param os the out stream to write to
 * @throws IOException if an I/O error occurs
 */
public void writeSpatialiteGeometry( Geometry geom, OutStream os ) throws IOException {
    // geom starts with byte 0x00
    buf[0] = 0x00;
    os.write(buf, 1);
    writeByteOrder(os);

    writeInt(geom.getSRID(), os);
    // 6 - 13 MBR_MIN_X a double value [little- big-endian ordered, accordingly with the
    // precedent one]
    // corresponding to the MBR minimum X coordinate for this GEOMETRY
    // 14 - 21 MBR_MIN_Y a double value corresponding to the MBR minimum Y coordinate
    // 22 - 29 MBR_MAX_X a double value corresponding to the MBR maximum X coordinate
    // 30 - 37 MBR_MAX_Y a double value corresponding to the MBR maximum Y coordinate
    Envelope envInt = geom.getEnvelopeInternal();
    writeDouble(envInt.getMinX(), os);
    writeDouble(envInt.getMinY(), os);
    writeDouble(envInt.getMaxX(), os);
    writeDouble(envInt.getMaxY(), os);

    // // 38 MBR_END [hex 7C] a GEOMETRY encoded BLOB value must always have an 0x7C byte in
    // this
    // // position
    buf[0] = 0x7C;
    os.write(buf, 1);

    if (geom instanceof Point)
        writePoint((Point) geom, os);
    // LinearRings will be written as LineStrings
    else if (geom instanceof LineString)
        writeLineString((LineString) geom, os);
    else if (geom instanceof Polygon)
        writePolygon((Polygon) geom, os);
    else if (geom instanceof MultiPoint)
        writeGeometryCollection(WKBConstants.wkbMultiPoint, (MultiPoint) geom, os);
    else if (geom instanceof MultiLineString)
        writeGeometryCollection(WKBConstants.wkbMultiLineString, (MultiLineString) geom, os);
    else if (geom instanceof MultiPolygon)
        writeGeometryCollection(WKBConstants.wkbMultiPolygon, (MultiPolygon) geom, os);
    else if (geom instanceof GeometryCollection)
        writeGeometryCollection(WKBConstants.wkbGeometryCollection, (GeometryCollection) geom, os);
    else {
        Assert.shouldNeverReachHere("Unknown Geometry type");
    }
}
 
Example 14
Source File: GeopackageCommonDb.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public String getSpatialindexGeometryWherePiece( String tableName, String alias, Geometry geometry ) throws Exception {
    // this is not possible in gpkg, backing on envelope intersection
    Envelope env = geometry.getEnvelopeInternal();
    return getSpatialindexBBoxWherePiece(tableName, alias, env.getMinX(), env.getMinY(), env.getMaxX(), env.getMaxY());
}
 
Example 15
Source File: LasTriangulation2Dsm.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@Execute
public void process() throws Exception {
    checkNull(inLas, inDtm, outRaster);

    GridCoverage2D inDtmGC = getRaster(inDtm);
    Polygon polygon = CoverageUtilities.getRegionPolygon(inDtmGC);
    CoordinateReferenceSystem crs = inDtmGC.getCoordinateReferenceSystem();

    List<Coordinate> lasCoordinates = new ArrayList<Coordinate>();
    pm.beginTask("Preparing triangulation...", -1);
    try (ALasDataManager lasData = ALasDataManager.getDataManager(new File(inLas), null, 0.0, crs)) {
        lasData.open();
        List<LasRecord> lasPoints = lasData.getPointsInGeometry(polygon, false);
        for( LasRecord lasRecord : lasPoints ) {
            lasCoordinates.add(new Coordinate(lasRecord.x, lasRecord.y, lasRecord.z));
        }
    }

    DelaunayTriangulationBuilder triangulationBuilder = new DelaunayTriangulationBuilder();
    triangulationBuilder.setSites(lasCoordinates);
    Geometry triangles = triangulationBuilder.getTriangles(gf);
    pm.done();

    int numTriangles = triangles.getNumGeometries();
    pm.beginTask("Extracting triangles based on threshold...", numTriangles);
    ArrayList<Geometry> trianglesList = new ArrayList<Geometry>();
    for( int i = 0; i < numTriangles; i++ ) {
        pm.worked(1);
        Geometry geometryN = triangles.getGeometryN(i);
        Coordinate[] coordinates = geometryN.getCoordinates();
        double diff1 = abs(coordinates[0].z - coordinates[1].z);
        if (diff1 > pElevThres) {
            continue;
        }
        double diff2 = abs(coordinates[0].z - coordinates[2].z);
        if (diff2 > pElevThres) {
            continue;
        }
        double diff3 = abs(coordinates[1].z - coordinates[2].z);
        if (diff3 > pElevThres) {
            continue;
        }
        trianglesList.add(geometryN);
    }
    pm.done();

    int newNumTriangles = trianglesList.size();
    int removedNum = numTriangles - newNumTriangles;
    pm.message("Original triangles: " + numTriangles);
    pm.message("New triangles: " + newNumTriangles);
    pm.message("Removed triangles: " + removedNum);

    pm.beginTask("Create triangles index...", newNumTriangles);
    final STRtree tree = new STRtree(trianglesList.size());
    for( Geometry triangle : trianglesList ) {
        Envelope env = triangle.getEnvelopeInternal();
        tree.insert(env, triangle);
        pm.worked(1);
    }
    pm.done();

    RegionMap regionMap = CoverageUtilities.getRegionParamsFromGridCoverage(inDtmGC);
    double north = regionMap.getNorth();
    double south = regionMap.getSouth();
    double east = regionMap.getEast();
    double west = regionMap.getWest();

    if (pXres == null || pYres == null) {
        pXres = regionMap.getXres();
        pYres = regionMap.getYres();
    }
    final int newRows = (int) round((north - south) / pYres);
    int newCols = (int) round((east - west) / pXres);

    final GridGeometry2D newGridGeometry2D = CoverageUtilities.gridGeometryFromRegionValues(north, south, east, west,
            newCols, newRows, crs);
    RegionMap newRegionMap = CoverageUtilities.gridGeometry2RegionParamsMap(newGridGeometry2D);
    final WritableRaster newWR = CoverageUtilities.createWritableRaster(newCols, newRows, null, null,
            HMConstants.doubleNovalue);

    ThreadedRunnable< ? > runner = new ThreadedRunnable(getDefaultThreadsNum(), null);
    pm.beginTask("Setting raster points...", newCols);
    for( int c = 0; c < newCols; c++ ) {
        final int fCol = c;
        runner.executeRunnable(new Runnable(){
            public void run() {
                try {
                    makeRow(tree, newRows, newGridGeometry2D, newWR, fCol);
                } catch (TransformException e) {
                    e.printStackTrace();
                }
                pm.worked(1);
            }
        });
    }
    runner.waitAndClose();
    pm.done();

    GridCoverage2D outRasterGC = CoverageUtilities.buildCoverage("outraster", newWR, newRegionMap, crs);
    dumpRaster(outRasterGC, outRaster);
}
 
Example 16
Source File: GeoPkgGeomWriter.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
void write(Geometry g, OutStream out) throws IOException {
    if (g == null) {
        return;
    }

    GeometryHeaderFlags flags = new GeometryHeaderFlags((byte) 0);

    flags.setBinaryType(GeopackageBinaryType.StandardGeoPackageBinary);
    flags.setEmpty(g.isEmpty());
    flags.setEndianess(ByteOrderValues.BIG_ENDIAN);
    flags.setEnvelopeIndicator(config.isWriteEnvelope() ? EnvelopeType.XY : EnvelopeType.NONE);

    GeometryHeader h = new GeometryHeader();
    h.setVersion((byte) 0);
    h.setFlags(flags);
    h.setSrid(g.getSRID());
    if (config.isWriteEnvelope()) {
        h.setEnvelope(g.getEnvelopeInternal());
    }

    // write out magic + flags + srid + envelope
    byte[] buf = new byte[8];
    buf[0] = 0x47;
    buf[1] = 0x50;
    buf[2] = h.getVersion();
    buf[3] = flags.toByte();
    out.write(buf, 4);

    int order = flags.getEndianess();
    ByteOrderValues.putInt(g.getSRID(), buf, order);
    out.write(buf, 4);

    if (flags.getEnvelopeIndicator() != EnvelopeType.NONE) {
        Envelope env = g.getEnvelopeInternal();
        ByteOrderValues.putDouble(env.getMinX(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMaxX(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMinY(), buf, order);
        out.write(buf, 8);

        ByteOrderValues.putDouble(env.getMaxY(), buf, order);
        out.write(buf, 8);
    }

    new WKBWriter(dim, order).write(g, out);
}
 
Example 17
Source File: GeopackageTableLayer.java    From geopaparazzi with GNU General Public License v3.0 4 votes vote down vote up
private long insertGeometry(ASpatialDb db, String tableName, Geometry geometry) throws Exception {
    int epsg = 4326;
    String pk = ((GPGeopackageDb) db).getPrimaryKey(tableName);
    long nextId = db.getLong("select max(" + pk + ") from " + tableName) + 1;

    IGeometryParser gp = db.getType().getGeometryParser();
    geometry.setSRID(epsg);
    Object obj = gp.toSqlObject(geometry);
    if (obj instanceof byte[]) {
        byte[] objBytes = (byte[]) obj;
        GeometryColumn gc = db.getGeometryColumnsForTable(tableName);
        String sql = "INSERT INTO " + tableName + " (" + pk + "," + gc.geometryColumnName + ") VALUES (?, ?)";

        db.execOnConnection(connection -> {
            try (IHMPreparedStatement pStmt = connection.prepareStatement(sql)) {
                pStmt.setLong(1, nextId);
                pStmt.setBytes(2, objBytes);
                pStmt.executeUpdate();
            }
            return null;
        });

        Envelope env = geometry.getEnvelopeInternal();
        double minX = env.getMinX();
        double maxX = env.getMaxX();
        double minY = env.getMinY();
        double maxY = env.getMaxY();

        try {
            // also update rtree index, since it is not supported
            String sqlTree = "INSERT OR REPLACE INTO rtree_" + tableName + "_" + gc.geometryColumnName +
                    " VALUES (" + nextId + "," + minX + ", " + maxX + "," + minY + ", " + maxY + ");";
            db.executeInsertUpdateDeleteSql(sqlTree);
        } catch (Exception e) {
            GPLog.error(this, "ERROR on rtree", e);
        }

        return nextId;
    }

    throw new IllegalArgumentException("Geometry object is not byte array.");
}
 
Example 18
Source File: DatabaseLasDataManager.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public synchronized List<LasRecord> getPointsInGeometry( Geometry checkGeom, boolean doOnlyEnvelope ) throws Exception {
    checkOpen();

    ArrayList<LasRecord> pointsListForTile = new ArrayList<LasRecord>();
    Envelope checkEnvelope = checkGeom.getEnvelopeInternal();
    PreparedGeometry preparedGeometry = null;
    if (!doOnlyEnvelope) {
        preparedGeometry = PreparedGeometryFactory.prepare(checkGeom);
    }
    final PreparedGeometry _preparedGeometry = preparedGeometry;
    List<LasCell> lasCells = LasCellsTable.getLasCells(spatialDb, checkGeom, true, true, false, false, false);
    lasCells.stream().forEach(cell -> {
        double[][] positions = LasCellsTable.getCellPositions(cell);
        short[][] cellIntensityClass = LasCellsTable.getCellIntensityClass(cell);

        for( int i = 0; i < positions.length; i++ ) {
            LasRecord dot = new LasRecord();
            dot.x = positions[i][0];
            dot.y = positions[i][1];
            dot.z = positions[i][2];

            Coordinate c = new Coordinate(dot.x, dot.y);
            if (doOnlyEnvelope && !checkEnvelope.contains(c)) {
                continue;
            } else if (!doOnlyEnvelope && !_preparedGeometry.contains(gf.createPoint(c))) {
                continue;
            }

            if (inDem != null) {
                double value = CoverageUtilities.getValue(inDem, c);
                if (HMConstants.isNovalue(value)) {
                    continue;
                }
                double height = dot.z - value;
                if (height > elevThreshold) {
                    dot.groundElevation = height;
                }
            }

            dot.intensity = cellIntensityClass[i][0];
            dot.classification = (byte) cellIntensityClass[i][1];

            pointsListForTile.add(dot);
        }
    });
    return pointsListForTile;
}
 
Example 19
Source File: ALasDataManager.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Retrieve all the envelope features that intersect the geometry.
 *
 * <p>an elev attribute is added with the max elev contained in the envelope.
 *
 * @param checkGeom the {@link org.locationtech.jts.geom.Geometry} to use to check.
 * @param doOnlyEnvelope check for the geom envelope instead of a intersection with it.
 * @param minMaxZI an array to be filled with the [minz,maxz, minintensity, maxintensity] to be used as style.
 * @param doPoints if <code>true</code>, create points instead of polygons.
 * @return the features of the envelopes contained in the supplied geometry.
 * @throws Exception
 */
public synchronized SimpleFeatureCollection getEnvelopeFeaturesInGeometry( Geometry checkGeom, boolean doOnlyEnvelope,
        double[] minMaxZI, boolean doPoints ) throws Exception {
    List<Geometry> envelopesInGeometry = getEnvelopesInGeometry(checkGeom, doOnlyEnvelope, null);

    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("overview");
    b.setCRS(crs);
    if (!doPoints) {
        b.add("the_geom", Polygon.class);
    } else {
        b.add("the_geom", Point.class);
    }
    b.add("elev", Double.class);
    b.add("intensity", Double.class);

    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    double minZ = Double.POSITIVE_INFINITY;
    double maxZ = Double.NEGATIVE_INFINITY;
    double minI = Double.POSITIVE_INFINITY;
    double maxI = Double.NEGATIVE_INFINITY;

    DefaultFeatureCollection newFeatures = new DefaultFeatureCollection();
    for( int i = 0; i < envelopesInGeometry.size(); i++ ) {
        Geometry geom = envelopesInGeometry.get(i);
        if (doPoints) {
            Envelope envelope = geom.getEnvelopeInternal();
            Coordinate centre = envelope.centre();
            geom = gf.createPoint(centre);
        }

        double elev = -9999.0;
        double intens = -9999.0;
        Object userData = geom.getUserData();
        if (userData instanceof double[]) {
            double[] data = (double[]) userData;
            elev = data[0];
            intens = data[1];
        }

        if (minMaxZI != null) {
            minZ = Math.min(minZ, elev);
            maxZ = Math.max(maxZ, elev);
            minI = Math.min(minI, intens);
            maxI = Math.max(maxI, intens);
        }

        Object[] objs = new Object[]{geom, elev, intens};
        builder.addAll(objs);
        SimpleFeature feature = builder.buildFeature(null);
        newFeatures.add(feature);
    }

    if (minMaxZI != null) {
        minMaxZI[0] = minZ;
        minMaxZI[1] = maxZ;
        minMaxZI[2] = minI;
        minMaxZI[3] = maxI;
    }
    return newFeatures;
}
 
Example 20
Source File: ReferencedEnvelope.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public ReferencedEnvelope(Geometry geometry) {
    this(geometry.getEnvelopeInternal(), geometry.getSRID());
}