org.locationtech.jts.geom.Envelope Java Examples

The following examples show how to use org.locationtech.jts.geom.Envelope. 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: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
private static double distanceToDegrees(
    final CoordinateReferenceSystem crs,
    final Envelope env,
    final GeometryFactory factory,
    final double meters) throws TransformException {
  return Collections.max(
      Arrays.asList(
          distanceToDegrees(
              crs,
              factory.createPoint(new Coordinate(env.getMaxX(), env.getMaxY())),
              meters),
          distanceToDegrees(
              crs,
              factory.createPoint(new Coordinate(env.getMaxX(), env.getMinY())),
              meters),
          distanceToDegrees(
              crs,
              factory.createPoint(new Coordinate(env.getMinX(), env.getMinY())),
              meters),
          distanceToDegrees(
              crs,
              factory.createPoint(new Coordinate(env.getMinX(), env.getMaxY())),
              meters)));
}
 
Example #2
Source File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 6 votes vote down vote up
@Override
public JexlNode getIndexQuery(ShardQueryConfiguration config, MetadataHelper helper, DateIndexHelper dateIndexHelper, Set<String> datatypeFilter) {
    int maxEnvelopes = Math.max(1, config.getGeoWaveMaxEnvelopes());
    if (isSpatialRelationship(name)) {
        Geometry geom = AbstractGeometryNormalizer.parseGeometry(args.get(1).image);
        List<Envelope> envelopes = getSeparateEnvelopes(geom, maxEnvelopes);
        if (!envelopes.isEmpty()) {
            
            JexlNode indexNode;
            if (envelopes.size() == 1) {
                indexNode = getIndexNode(args.get(0), envelopes.get(0), config, helper);
            } else {
                indexNode = getIndexNode(args.get(0), envelopes, config, helper);
            }
            
            return indexNode;
        }
    }
    // return the true node if unable to parse arguments
    return TRUE_NODE;
}
 
Example #3
Source File: TestUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTiles2() throws Exception {
    int zoomLevel = 8;
    double tolerance = 0.0000001;

    Coordinate c1 = new Coordinate(1289079.2130195359, 5900910.886700573);
    Coordinate c2 = new Coordinate(1298888.6991376826, 5909656.474824957);
    Envelope env3857 = new Envelope(c1, c2);
    Envelope env4326 = MercatorUtils.convert3857To4326(env3857);

    Coordinate centre = env4326.centre();
    assertTrue(centre.equals2D(new Coordinate(11.62405565150858, 46.77412159831822), tolerance));

    int[] tileNumberFrom3857 = MercatorUtils.getTileNumberFrom3857(env3857.centre(), zoomLevel);
    assertEquals(136, tileNumberFrom3857[1]);
    assertEquals(90, tileNumberFrom3857[2]);
    assertEquals(8, tileNumberFrom3857[0]);

}
 
Example #4
Source File: DatabaseLasDataManager.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized List<Geometry> getEnvelopesInGeometry( Geometry checkGeom, boolean doOnlyEnvelope, double[] minMaxZ )
        throws Exception {
    checkOpen();

    List<LasCell> lasCells = LasCellsTable.getLasCells(spatialDb, checkGeom, true, false, false, false, false);

    double minZ = Double.POSITIVE_INFINITY;
    double maxZ = Double.NEGATIVE_INFINITY;
    Envelope env = new Envelope();
    for( LasCell lasCell : lasCells ) {
        minZ = Math.min(minZ, lasCell.minElev);
        maxZ = Math.max(maxZ, lasCell.maxElev);
        env.expandToInclude(lasCell.polygon.getEnvelopeInternal());
    }

    ReferencedEnvelope3D dataEnvelope = new ReferencedEnvelope3D(env.getMinX(), env.getMaxX(), env.getMinY(), env.getMaxY(),
            minZ, maxZ, crs);
    Polygon envelopePolygon = LasIndexer.envelopeToPolygon(dataEnvelope);
    ArrayList<Geometry> envelopeList = new ArrayList<Geometry>();
    envelopeList.add(envelopePolygon);
    return envelopeList;
}
 
Example #5
Source File: GeoWaveFunctionsDescriptor.java    From datawave with Apache License 2.0 6 votes vote down vote up
protected static JexlNode getIndexNode(String fieldName, List<Envelope> envs, ShardQueryConfiguration config, MetadataHelper helper) {
    Index index;
    int maxExpansion;
    if (isOnlyPointType(fieldName, helper)) {
        index = PointNormalizer.index;
        maxExpansion = config.getPointMaxExpansion();
    } else {
        index = GeometryNormalizer.index;
        maxExpansion = config.getGeometryMaxExpansion();
    }
    
    Collection<ByteArrayRange> allRanges = new ArrayList<>();
    int maxRanges = maxExpansion / envs.size();
    for (Envelope env : envs) {
        for (MultiDimensionalNumericData range : GeometryUtils.basicConstraintsFromEnvelope(env).getIndexConstraints(index)) {
            allRanges.addAll(index.getIndexStrategy().getQueryRanges(range, maxRanges).getCompositeQueryRanges());
        }
    }
    allRanges = ByteArrayRange.mergeIntersections(allRanges, ByteArrayRange.MergeOperation.UNION);
    
    Iterable<JexlNode> rangeNodes = Iterables.transform(allRanges, new ByteArrayRangeToJexlNode(fieldName));
    
    // now link em up
    return JexlNodeFactory.createOrNode(rangeNodes);
}
 
Example #6
Source File: TestUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testTiles() throws Exception {
    int tx = 0;
    int ty = 0;
    int tz = 0;

    Envelope env4326 = MercatorUtils.tileBounds4326(tx, ty, tz);
    Envelope env3857 = MercatorUtils.tileBounds3857(tx, ty, tz);

    Coordinate ll3857 = new Coordinate(env3857.getMinX(), env3857.getMinY());
    Coordinate ur3857 = new Coordinate(env3857.getMaxX(), env3857.getMaxY());

    Coordinate ll4326transf = MercatorUtils.convert3857To4326(ll3857);
    Coordinate ur4326transf = MercatorUtils.convert3857To4326(ur3857);
    Coordinate ll4326 = new Coordinate(env4326.getMinX(), env4326.getMinY());
    Coordinate ur4326 = new Coordinate(env4326.getMaxX(), env4326.getMaxY());

    double tolerance = 0.0000001;
    assertTrue(ll4326transf.equals2D(ll4326, tolerance));
    assertTrue(ur4326transf.equals2D(ur4326, tolerance));
}
 
Example #7
Source File: GeopackageCommonDb.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void initEntry( IHMResultSet rs, Entry e ) throws Exception {
    e.setIdentifier(rs.getString("identifier"));
    e.setDescription(rs.getString("description"));
    e.setTableName(rs.getString("table_name"));
    try {
        final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_STRING);
        DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT"));
        e.setLastChange(DATE_FORMAT.parse(rs.getString("last_change")));
    } catch (ParseException ex) {
        throw new IOException(ex);
    }

    int srid = rs.getInt("srs_id");
    e.setSrid(srid);
    e.setBounds(new Envelope(rs.getDouble("min_x"), rs.getDouble("max_x"), rs.getDouble("min_y"), rs.getDouble("max_y")));
}
 
Example #8
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 #9
Source File: RL2NwwLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public RL2NwwLayer( Rasterlite2Coverage rasterCoverage, Integer tileSize ) throws Exception {
    super(makeLevels(rasterCoverage, tileSize));
    this.layerName = rasterCoverage.getName();

    Envelope bounds = rasterCoverage.getBounds();
    double w = bounds.getMinX();
    double s = bounds.getMinY();
    double e = bounds.getMaxX();
    double n = bounds.getMaxY();

    double centerX = w + (e - w) / 2.0;
    double centerY = s + (n - s) / 2.0;
    Coordinate centerCoordinate = new Coordinate(centerX, centerY);

    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
    CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromSrid(rasterCoverage.getSrid());

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
    centerCoordinateLL = JTS.transform(centerCoordinate, null, transform);

    this.setUseTransparentTextures(true);

}
 
Example #10
Source File: ExtractGeometryFilterVisitorTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testIntersects() throws CQLException, TransformException, ParseException {

  final Filter filter =
      CQL.toFilter(
          String.format(
              "INTERSECTS(%s, POLYGON((0 0, 0 25, 10 25, 10 0, 0 0)))",
              geomAttributeName));
  final Query query = new Query("type", filter);

  final ExtractGeometryFilterVisitorResult result =
      (ExtractGeometryFilterVisitorResult) query.getFilter().accept(visitorWithDescriptor, null);

  final Envelope bounds = new Envelope(0, 10, 0, 25);
  final Geometry bbox = new GeometryFactory().toGeometry(bounds);

  assertTrue(bbox.equalsTopo(result.getGeometry()));
  assertTrue(result.getCompareOp() == CompareOperation.INTERSECTS);
}
 
Example #11
Source File: AbstractGeoWaveBasicVectorIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
private static void validateBBox(final Envelope bboxStat, final StatisticsCache cachedValue) {
  Assert.assertNotNull(bboxStat);
  Assert.assertEquals(
      "The min X of the bounding box stat does not match the expected value",
      cachedValue.minX,
      bboxStat.getMinX(),
      MathUtils.EPSILON);
  Assert.assertEquals(
      "The min Y of the bounding box stat does not match the expected value",
      cachedValue.minY,
      bboxStat.getMinY(),
      MathUtils.EPSILON);
  Assert.assertEquals(
      "The max X of the bounding box stat does not match the expected value",
      cachedValue.maxX,
      bboxStat.getMaxX(),
      MathUtils.EPSILON);
  Assert.assertEquals(
      "The max Y of the bounding box stat does not match the expected value",
      cachedValue.maxY,
      bboxStat.getMaxY(),
      MathUtils.EPSILON);
}
 
Example #12
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 #13
Source File: FeatureUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a {@link Polygon} from an {@link Envelope}.
 * 
 * @param envelope the envelope to convert.
 * @return the created polygon.
 */
public static Polygon envelopeToPolygon( Envelope envelope ) {
    double w = envelope.getMinX();
    double e = envelope.getMaxX();
    double s = envelope.getMinY();
    double n = envelope.getMaxY();

    Coordinate[] coords = new Coordinate[5];
    coords[0] = new Coordinate(w, n);
    coords[1] = new Coordinate(e, n);
    coords[2] = new Coordinate(e, s);
    coords[3] = new Coordinate(w, s);
    coords[4] = new Coordinate(w, n);

    GeometryFactory gf = GeometryUtilities.gf();
    LinearRing linearRing = gf.createLinearRing(coords);
    Polygon polygon = gf.createPolygon(linearRing, null);
    return polygon;
}
 
Example #14
Source File: ExtractGeometryFilterVisitorTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithMultipleAttributes() throws CQLException, TransformException, ParseException {

  // In this test query, we have constrains over multiple geometric
  // attributes.
  // The ExtractGeometryFilterVisitor class should only extracts
  // geometric constrains associated with the specified attribute name and
  // ignore others.
  final Filter filter =
      CQL.toFilter(
          String.format(
              "INTERSECTS(%s, POLYGON((0 0, 0 25, 10 25, 10 0, 0 0))) AND INTERSECTS(geomOtherAttr, POLYGON((0 0, 0 5, 5 5, 5 0, 0 0)))",
              geomAttributeName));
  final Query query = new Query("type", filter);

  final ExtractGeometryFilterVisitorResult result =
      (ExtractGeometryFilterVisitorResult) query.getFilter().accept(visitorWithDescriptor, null);

  final Envelope bounds = new Envelope(0, 10, 0, 25);
  final Geometry bbox = new GeometryFactory().toGeometry(bounds);

  assertTrue(bbox.equalsTopo(result.getGeometry()));
  assertTrue(result.getCompareOp() == null);
}
 
Example #15
Source File: TestTransformationUtils.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void testTransformationUtils() throws Exception {
    Envelope env = new Envelope(100, 200, 1000, 5000);
    Rectangle rect = new Rectangle(0, 0, 100, 4000);

    AffineTransform worldToPixel = TransformationUtils.getWorldToPixel(env, rect);

    Point2D srcPt = new Point2D.Double(150.0, 3000.0);
    Point2D transformed = worldToPixel.transform(srcPt, null);
    assertEquals(50, (int) transformed.getX());
    assertEquals(2000, (int) transformed.getY());

    srcPt = new Point2D.Double(100.0, 1000.0);
    transformed = worldToPixel.transform(srcPt, null);
    assertEquals(0, (int) transformed.getX());
    assertEquals(4000, (int) transformed.getY());
}
 
Example #16
Source File: TestRasterlite2.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void testReading() throws Exception {
    URL dataUrl = TestRasterlite2.class.getClassLoader().getResource("1873.berlin_stadt_postgrenzen_rasterlite2.rl2");
    File file = new File(dataUrl.toURI());

    try (ASpatialDb db = EDb.SPATIALITE.getSpatialDb()) {
        db.open(file.getAbsolutePath());
        Rasterlite2Db rdb = new Rasterlite2Db(db);
        List<Rasterlite2Coverage> rasterCoverages = rdb.getRasterCoverages(true);

        Rasterlite2Coverage raster = rasterCoverages.get(2);
        assertEquals("berlin_stadtteilgrenzen.1880", raster.getName());

        Envelope bounds = raster.getBounds();
        
    }

}
 
Example #17
Source File: ExtractGeometryFilterVisitorTest.java    From geowave with Apache License 2.0 6 votes vote down vote up
@Test
public void testContains() throws CQLException, TransformException, ParseException {

  final Filter filter =
      CQL.toFilter(
          String.format(
              "CONTAINS(geom, POLYGON((0 0, 0 25, 10 25, 10 0, 0 0)))",
              geomAttributeName));
  final Query query = new Query("type", filter);

  final ExtractGeometryFilterVisitorResult result =
      (ExtractGeometryFilterVisitorResult) query.getFilter().accept(visitorWithDescriptor, null);

  final Envelope bounds = new Envelope(0, 10, 0, 25);
  final Geometry bbox = new GeometryFactory().toGeometry(bounds);

  assertTrue(bbox.equalsTopo(result.getGeometry()));
  assertTrue(result.getCompareOp() == CompareOperation.WITHIN);
}
 
Example #18
Source File: Sentinel2ImageryProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
/** Returns the Product/Scene collection that matches the specified criteria. */
public abstract Iterator<SimpleFeature> searchScenes(
    final File scenesDir,
    final String collection,
    final String platform,
    final String location,
    final Envelope envelope,
    final Date startDate,
    final Date endDate,
    final int orbitNumber,
    final int relativeOrbitNumber) throws IOException;
 
Example #19
Source File: GeoWaveRasterReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private CloseableIterator<GridCoverage> queryForTiles(
    final Rectangle pixelDimension,
    final GeneralEnvelope requestEnvelope,
    final double levelResX,
    final double levelResY,
    final RasterDataAdapter adapter) throws IOException {
  final QueryConstraints query;
  if (requestEnvelope.getCoordinateReferenceSystem() != null) {
    query =
        new IndexOnlySpatialQuery(
            new GeometryFactory().toGeometry(
                new Envelope(
                    requestEnvelope.getMinimum(0),
                    requestEnvelope.getMaximum(0),
                    requestEnvelope.getMinimum(1),
                    requestEnvelope.getMaximum(1))),
            GeometryUtils.getCrsCode(requestEnvelope.getCoordinateReferenceSystem()));
  } else {
    query =
        new IndexOnlySpatialQuery(
            new GeometryFactory().toGeometry(
                new Envelope(
                    requestEnvelope.getMinimum(0),
                    requestEnvelope.getMaximum(0),
                    requestEnvelope.getMinimum(1),
                    requestEnvelope.getMaximum(1))));
  }
  return queryForTiles(
      adapter,
      query,
      new double[] {levelResX * adapter.getTileSize(), levelResY * adapter.getTileSize()});
}
 
Example #20
Source File: AnalyzeRunner.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void nextScene(final SimpleFeature currentBand) {
  printSceneInfo();
  sceneCount++;
  entityBandIdToSimpleFeatureMap.clear();
  final int path = (int) currentBand.getAttribute(SceneFeatureIterator.PATH_ATTRIBUTE_NAME);
  final int row = (int) currentBand.getAttribute(SceneFeatureIterator.ROW_ATTRIBUTE_NAME);
  final float cloudCover =
      (float) currentBand.getAttribute(SceneFeatureIterator.CLOUD_COVER_ATTRIBUTE_NAME);
  final String processingLevel =
      (String) currentBand.getAttribute(SceneFeatureIterator.PROCESSING_LEVEL_ATTRIBUTE_NAME);
  final Date date =
      (Date) currentBand.getAttribute(SceneFeatureIterator.ACQUISITION_DATE_ATTRIBUTE_NAME);
  minRow = Math.min(minRow, row);
  maxRow = Math.max(maxRow, row);
  minPath = Math.min(minPath, path);
  maxPath = Math.max(maxPath, path);
  final Envelope env = ((Geometry) currentBand.getDefaultGeometry()).getEnvelopeInternal();
  minLat = Math.min(minLat, env.getMinY());
  maxLat = Math.max(maxLat, env.getMaxY());
  minLon = Math.min(minLon, env.getMinX());
  maxLon = Math.max(maxLon, env.getMaxX());

  minCloudCover = Math.min(minCloudCover, cloudCover);
  maxCloudCover = Math.max(maxCloudCover, cloudCover);
  totalCloudCover += cloudCover;

  Integer count = processingLevelCounts.get(processingLevel);
  if (count == null) {
    count = 0;
  }
  processingLevelCounts.put(processingLevel, ++count);

  startDate = Math.min(startDate, date.getTime());
  endDate = Math.max(endDate, date.getTime());
  wrs2Keys.add(new WRS2Key(path, row));
}
 
Example #21
Source File: TestGeopackage.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTilesGeotools() throws Exception {

    URL dataUrl = TestGeopackage.class.getClassLoader().getResource("test_tiles_srid.gpkg");
    File gpkgFile = new File(dataUrl.toURI());
    try (GeopackageCommonDb db = (GeopackageCommonDb) EDb.GEOPACKAGE.getSpatialDb()) {
        db.open(gpkgFile.getAbsolutePath());
        db.initSpatialMetadata(null);

        HashMap<String, List<String>> tablesMap = db.getTablesMap(false);
        List<String> tables = tablesMap.get(GeopackageTableNames.USERDATA);
        assertEquals(1, tables.size());

        List<Entry> contents = db.contents();
        assertEquals(1, contents.size());

        TileEntry tileEntry = db.tile("test");
        assertNotNull(tileEntry);

        int srid = tileEntry.getSrid();
        assertEquals(3857, srid);

        Envelope bounds = tileEntry.getBounds();
        double delta = 0.000001;
        assertEquals(-1.50672670155739E7, bounds.getMinX(), delta);
        assertEquals(8570731.107560242, bounds.getMinY(), delta);
        assertEquals(-1.502813125709188E7, bounds.getMaxX(), delta);
        assertEquals(8609866.86604225, bounds.getMaxY(), delta);

        Envelope tileMatrixSetBounds = tileEntry.getTileMatrixSetBounds();
        assertEquals(-1.50672670155739E7, tileMatrixSetBounds.getMinX(), delta);
        assertEquals(8548683.634461217, tileMatrixSetBounds.getMinY(), delta);
        assertEquals(-1.500608378399286E7, tileMatrixSetBounds.getMaxX(), delta);
        assertEquals(8609866.86604225, tileMatrixSetBounds.getMaxY(), delta);

        List<TileMatrix> tileMatricies = tileEntry.getTileMatricies();
        assertEquals(3, tileMatricies.size());
    }
}
 
Example #22
Source File: TestTransformationUtils.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testTransformationUtils3() throws Exception {
    Envelope env = new Envelope(100, 200, 1000, 5000);
    double newWidth = 50.0;
    double newHeight = 2000;

    Envelope scaled = TransformationUtils.scaleToWidth(env, newWidth);
    assertEquals(100.0, scaled.getMinX());
    assertEquals(1000.0, scaled.getMinY());
    assertEquals(50.0, scaled.getWidth());
    assertEquals(2000.0, scaled.getHeight());

    scaled = TransformationUtils.scaleToHeight(env, newHeight);
    assertEquals(100.0, scaled.getMinX());
    assertEquals(1000.0, scaled.getMinY());
    assertEquals(50.0, scaled.getWidth());
    assertEquals(2000.0, scaled.getHeight());

    newWidth = 300.0;
    newHeight = 12000.0;
    scaled = TransformationUtils.scaleToWidth(env, newWidth);
    assertEquals(100.0, scaled.getMinX());
    assertEquals(1000.0, scaled.getMinY());
    assertEquals(300.0, scaled.getWidth());
    assertEquals(12000.0, scaled.getHeight());
    scaled = TransformationUtils.scaleToHeight(env, newHeight);
    assertEquals(100.0, scaled.getMinX());
    assertEquals(1000.0, scaled.getMinY());
    assertEquals(300.0, scaled.getWidth());
    assertEquals(12000.0, scaled.getHeight());
}
 
Example #23
Source File: TransformationUtils.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the affine transform that brings from the world envelope to the rectangle. 
 * 
 * @param worldEnvelope the envelope.
 * @param pixelRectangle the destination rectangle.
 * @return the transform.
 */
public static AffineTransform getWorldToPixel( Envelope worldEnvelope, Rectangle pixelRectangle ) {
    double width = pixelRectangle.getWidth();
    double worldWidth = worldEnvelope.getWidth();
    double height = pixelRectangle.getHeight();
    double worldHeight = worldEnvelope.getHeight();

    AffineTransform translate = AffineTransform.getTranslateInstance(-worldEnvelope.getMinX(), -worldEnvelope.getMinY());
    AffineTransform scale = AffineTransform.getScaleInstance(width / worldWidth, height / worldHeight);
    AffineTransform mirror_y = new AffineTransform(1, 0, 0, -1, 0, pixelRectangle.getHeight());
    AffineTransform world2pixel = new AffineTransform(mirror_y);
    world2pixel.concatenate(scale);
    world2pixel.concatenate(translate);
    return world2pixel;
}
 
Example #24
Source File: GrassLegacyUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static Envelope reprojectEnvelopeByEpsg( int srcEpsg, int destEpsg, Envelope srcEnvelope )
        throws FactoryException, TransformException {

    CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromSrid(srcEpsg);
    CoordinateReferenceSystem targetCRS = CrsUtilities.getCrsFromSrid(destEpsg);
    MathTransform tr = CRS.findMathTransform(sourceCRS, targetCRS);

    // From that point, I'm not sure which kind of object is returned by
    // getLatLonBoundingBox(). But there is some convenience methods if CRS
    // like:

    return JTS.transform(srcEnvelope, tr);

}
 
Example #25
Source File: RandomGeometryBuilder.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
public Map<String,Object> toMap(Envelope envelope) {
    final Map<String,Object> properties = new HashMap<>();
    final List<List<Double>> coordinates = new ArrayList<>();
    coordinates.add(Arrays.asList(envelope.getMinX(), envelope.getMaxY()));
    coordinates.add(Arrays.asList(envelope.getMaxX(), envelope.getMinY()));
    properties.put("type", "envelope");
    properties.put("coordinates", coordinates);
    return properties;
}
 
Example #26
Source File: FeatureGeometryUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static Envelope getGeoBounds(
    final DataStorePluginOptions dataStorePlugin,
    final String typeName,
    final String geomField) {
  final DataStatisticsStore statisticsStore = dataStorePlugin.createDataStatisticsStore();
  final InternalAdapterStore internalAdapterStore = dataStorePlugin.createInternalAdapterStore();
  final short adapterId = internalAdapterStore.getAdapterId(typeName);
  final StatisticsQuery<Envelope> query =
      VectorStatisticsQueryBuilder.newBuilder().factory().bbox().fieldName(geomField).build();
  try (final CloseableIterator<InternalDataStatistics<?, ?, ?>> geoStatIt =
      statisticsStore.getDataStatistics(
          adapterId,
          query.getExtendedId(),
          query.getStatsType(),
          query.getAuthorizations())) {
    if (geoStatIt.hasNext()) {
      final InternalDataStatistics<?, ?, ?> geoStat = geoStatIt.next();
      if (geoStat != null) {
        if (geoStat instanceof FeatureBoundingBoxStatistics) {
          final FeatureBoundingBoxStatistics bbStats = (FeatureBoundingBoxStatistics) geoStat;
          return new Envelope(
              bbStats.getMinX(),
              bbStats.getMaxX(),
              bbStats.getMinY(),
              bbStats.getMaxY());
        }
      }
    }
  }
  return null;
}
 
Example #27
Source File: AnalyzeRunner.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void nextScene(final SimpleFeature currentBand) {
  printSceneInfo();
  sceneCount++;
  entityBandIdToSimpleFeatureMap.clear();

  final Envelope env = ((Geometry) currentBand.getDefaultGeometry()).getEnvelopeInternal();
  final Date date =
      (Date) currentBand.getAttribute(SceneFeatureIterator.ACQUISITION_DATE_ATTRIBUTE_NAME);
  final String processingLevel =
      (String) currentBand.getAttribute(SceneFeatureIterator.PROCESSING_LEVEL_ATTRIBUTE_NAME);
  final int cloudCover =
      (int) currentBand.getAttribute(SceneFeatureIterator.CLOUD_COVER_ATTRIBUTE_NAME);

  minLat = Math.min(minLat, env.getMinY());
  maxLat = Math.max(maxLat, env.getMaxY());
  minLon = Math.min(minLon, env.getMinX());
  maxLon = Math.max(maxLon, env.getMaxX());

  startDate = Math.min(startDate, date.getTime());
  endDate = Math.max(endDate, date.getTime());

  Integer count = processingLevelCounts.get(processingLevel);
  if (count == null) {
    count = 0;
  }
  processingLevelCounts.put(processingLevel, ++count);

  minCloudCover = Math.min(minCloudCover, cloudCover);
  maxCloudCover = Math.max(maxCloudCover, cloudCover);
  totalCloudCover += cloudCover;
}
 
Example #28
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 #29
Source File: ReferencedEnvelopeTest.java    From arctic-sea with Apache License 2.0 5 votes vote down vote up
@Test
public void testHashCode() {
    final ReferencedEnvelope anEnvelope = new ReferencedEnvelope(new Envelope(1.0, 2.0, 3.0, 4.0), 52);
    final ReferencedEnvelope anotherEnvelope = new ReferencedEnvelope(null, 52);
    assertThat(anEnvelope.hashCode(), is(anEnvelope.hashCode()));
    assertThat(anEnvelope.hashCode(), is(not(anotherEnvelope.hashCode())));
}
 
Example #30
Source File: PagesRTreeIndex.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Envelope getEnvelope(OGCGeometry ogcGeometry)
{
    com.esri.core.geometry.Envelope env = new com.esri.core.geometry.Envelope();
    ogcGeometry.getEsriGeometry().queryEnvelope(env);

    return new Envelope(env.getXMin(), env.getXMax(), env.getYMin(), env.getYMax());
}