Java Code Examples for org.geotools.geometry.jts.ReferencedEnvelope#transform()

The following examples show how to use org.geotools.geometry.jts.ReferencedEnvelope#transform() . 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: ImageGenerator.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
private void expandToIncludeEnvelope( ReferencedEnvelope maxExtent, org.opengis.geometry.Envelope envelope ) {
    ReferencedEnvelope tmpExtent = new ReferencedEnvelope(envelope.getCoordinateReferenceSystem());
    DirectPosition ll = envelope.getLowerCorner();
    double[] coordinate = ll.getCoordinate();
    tmpExtent.expandToInclude(new Coordinate(coordinate[0], coordinate[1]));
    DirectPosition ur = envelope.getUpperCorner();
    coordinate = ur.getCoordinate();
    tmpExtent.expandToInclude(new Coordinate(coordinate[0], coordinate[1]));

    try {
        ReferencedEnvelope transformed = tmpExtent.transform(maxExtent.getCoordinateReferenceSystem(), true);
        maxExtent.expandToInclude(transformed);
    } catch (TransformException | FactoryException e) {
        e.printStackTrace();
    }
}
 
Example 2
Source File: ImageMosaicNwwLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public ImageMosaicNwwLayer( File imageMosaicShpFile, Integer tileSize, GeneralParameterValue[] gp,
        boolean removeSameColorImages ) throws Exception {
    super(makeLevels(imageMosaicShpFile, getRenderer(imageMosaicShpFile, gp), tileSize, removeSameColorImages));
    this.layerName = FileUtilities.getNameWithoutExtention(imageMosaicShpFile);

    ReferencedEnvelope envelope = OmsVectorReader.readEnvelope(imageMosaicShpFile.getAbsolutePath());
    ReferencedEnvelope envelopeLL = envelope.transform(DefaultGeographicCRS.WGS84, true);

    double w = envelopeLL.getMinX();
    double s = envelopeLL.getMinY();
    double e = envelopeLL.getMaxX();
    double n = envelopeLL.getMaxY();

    double centerX = w + (e - w) / 2.0;
    double centerY = s + (n - s) / 2.0;

    centerCoordinate = new Coordinate(centerX, centerY);

    this.setUseTransparentTextures(true);

}
 
Example 3
Source File: RasterizedSpatialiteLasLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public RasterizedSpatialiteLasLayer( String title, ASpatialDb db, Integer tileSize, boolean transparentBackground,
        boolean doIntensity ) throws Exception {
    super(makeLevels(title, tileSize, transparentBackground, db, doIntensity));
    String plus = doIntensity ? INTENSITY : ELEVATION;
    this.layerName = title + " " + plus;
    this.setUseTransparentTextures(true);

    try {
        Envelope tableBounds = db.getTableBounds(LasSourcesTable.TABLENAME);
        GeometryColumn spatialiteGeometryColumns = db.getGeometryColumnsForTable(LasCellsTable.TABLENAME);
        CoordinateReferenceSystem dataCrs = CRS.decode("EPSG:" + spatialiteGeometryColumns.srid);
        CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
        ReferencedEnvelope env = new ReferencedEnvelope(tableBounds, dataCrs);
        ReferencedEnvelope envLL = env.transform(targetCRS, true);

        centre = envLL.centre();
    } catch (Exception e) {
        e.printStackTrace();
        centre = CrsUtilities.WORLD.centre();
    }
}
 
Example 4
Source File: MosaicFormModel.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
public Product getBoundaryProduct() throws FactoryException, TransformException {
    final CoordinateReferenceSystem mapCRS = getTargetCRS();
    if (mapCRS != null) {
        final ReferencedEnvelope envelope = getTargetEnvelope();
        final Envelope mapEnvelope = envelope.transform(mapCRS, true);

        final double pixelSizeX = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_X);
        final double pixelSizeY = (Double) getPropertyValue(PROPERTY_PIXEL_SIZE_Y);
        final int w = MathUtils.floorInt(mapEnvelope.getSpan(0) / pixelSizeX);
        final int h = MathUtils.floorInt(mapEnvelope.getSpan(1) / pixelSizeY);

        final Product product = new Product("mosaic", "MosaicBounds", w, h);
        final GeoCoding geoCoding = new CrsGeoCoding(mapCRS,
                                                     w, h,
                                                     mapEnvelope.getMinimum(0),
                                                     mapEnvelope.getMaximum(1),
                                                     pixelSizeX, pixelSizeY);
        product.setSceneGeoCoding(geoCoding);

        return product;
    }
    return null;
}
 
Example 5
Source File: RasterUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static ReferencedEnvelope getReferenceEnvelope(
    final GridCoverage gridCoverage,
    final CoordinateReferenceSystem targetCrs) {
  final CoordinateReferenceSystem sourceCrs = gridCoverage.getCoordinateReferenceSystem();
  final Envelope sampleEnvelope = gridCoverage.getEnvelope();

  final ReferencedEnvelope sampleReferencedEnvelope =
      new ReferencedEnvelope(
          new org.locationtech.jts.geom.Envelope(
              sampleEnvelope.getMinimum(0),
              sampleEnvelope.getMaximum(0),
              sampleEnvelope.getMinimum(1),
              sampleEnvelope.getMaximum(1)),
          gridCoverage.getCoordinateReferenceSystem());

  ReferencedEnvelope projectedReferenceEnvelope = sampleReferencedEnvelope;
  if ((targetCrs != null) && !targetCrs.equals(sourceCrs)) {
    try {
      projectedReferenceEnvelope = sampleReferencedEnvelope.transform(targetCrs, true);
    } catch (TransformException | FactoryException e) {
      LOGGER.warn("Unable to transform envelope of grid coverage to " + targetCrs.getName(), e);
    }
  }
  return projectedReferenceEnvelope;
}
 
Example 6
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION")
public Bbox transform(Bbox source, CrsTransform crsTransform) {
	try {
		if (crsTransform.isTransforming()) {
			Envelope envelope = new Envelope(source.getX(), source.getMaxX(), source.getY(), source.getMaxY());
			Envelope transformableArea = crsTransform.getTransformableEnvelope();
			if (null != transformableArea) {
				envelope = envelope.intersection(transformableArea);
			}
			if (envelope.isNull()) {
				return new Bbox();
			} else {
				ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, crsTransform.getSource());
				envelope = refEnvelope.transform(crsTransform.getTarget(), true);
				return new Bbox(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight());
			}
		} else {
			return source;
		}
	} catch (Exception e) { // NOSONAR typically TopologyException, TransformException or FactoryException
		logBboxSuggestCrsTransformInfo(crsTransform.getId(), source, e);
		return new Bbox();
	}
}
 
Example 7
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION")
public Envelope transform(Envelope source, CrsTransform crsTransform) {
	try {
		if (crsTransform.isTransforming()) {
			Envelope transformableArea = crsTransform.getTransformableEnvelope();
			if (null != transformableArea) {
				source = source.intersection(transformableArea);
			}
			if (source.isNull()) {
				return source;
			} else {
				ReferencedEnvelope refEnvelope = new ReferencedEnvelope(source, crsTransform.getSource());
				return refEnvelope.transform(crsTransform.getTarget(), true);
			}
		} else {
			return source;
		}
	} catch (Exception e) { // NOSONAR typically TopologyException, TransformException or FactoryException
		logEnvelopeSuggestCrsTransformInfo(crsTransform.getId(), source, e);
		return new Envelope();
	}
}
 
Example 8
Source File: WmsWrapper.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static void main( String[] args ) throws Exception {
    String url = "https://gis.stmk.gv.at/arcgis/services/OGD/als_schummerung/MapServer/WmsServer?request=GetCapabilities&service=WMS";
    String wmscode = "EPSG:4326";
    int width = 1000;
    int height = 1000;
    String outputImage = "/home/hydrologis/TMP/VIENNA/wms.png";

    WmsWrapper ww = new WmsWrapper(url);
    ww.printInfo();
    Layer[] layers = ww.getLayers();
    for( Layer layer : layers ) {
        String name = layer.getName();
        if (name.equals("Digitales_Oberflaechenmodell_DOM")) {
            CRSEnvelope latLonBoundingBox = layer.getLatLonBoundingBox();
            double w = latLonBoundingBox.getMinX();
            double e = latLonBoundingBox.getMaxX();
            double s = latLonBoundingBox.getMinY();
            double n = latLonBoundingBox.getMaxY();
            ReferencedEnvelope env = new ReferencedEnvelope(w, e, s, n, CRS.decode("EPSG:4326"));

            ReferencedEnvelope wmsEnv = env.transform(CRS.decode(wmscode), false);
            BufferedImage image = ww.getImage(ww.getMapRequest(layer, null, wmscode, width, height, wmsEnv, null, null));
            String format = "jpg";
            if (outputImage.toLowerCase().endsWith("png")) {
                format = "png";
            }
            ImageIO.write(image, format, new File(outputImage));
            break;
        }
    }
}
 
Example 9
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CrsTransform getCrsTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	String key = getTransformKey(sourceCrs, targetCrs);
	CrsTransform transform = transformCache.get(key);
	if (null == transform) {
		MathTransform mathTransform = getBaseMathTransform(sourceCrs, targetCrs);

		// as there was no transformable area configured, try to build it instead
		Envelope transformableArea = null;
		try {
			org.opengis.geometry.Envelope ogEnvelope = CRS.getEnvelope(targetCrs);
			if (null != ogEnvelope) {
				Envelope envelope = new Envelope(ogEnvelope.getLowerCorner().getCoordinate()[0], ogEnvelope
						.getUpperCorner().getCoordinate()[0], ogEnvelope.getLowerCorner().getCoordinate()[1],
						ogEnvelope.getUpperCorner().getCoordinate()[1]);
				log.debug("CRS " + targetCrs.getId() + " envelope " + envelope);
				ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, targetCrs);
				transformableArea = refEnvelope.transform(sourceCrs, true);
				log.debug("transformable area for " + key + " is " + transformableArea);
			}
		} catch (MismatchedDimensionException mde) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					mde.getMessage()});
		} catch (TransformException te) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					te.getMessage()});
		} catch (FactoryException fe) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					fe.getMessage()});
		}

		transform = new CrsTransformImpl(key, sourceCrs, targetCrs, mathTransform, transformableArea);
		transformCache.put(key, transform);
	}
	return transform;
}
 
Example 10
Source File: GeoHashGrid.java    From elasticgeo with GNU General Public License v3.0 4 votes vote down vote up
public void initalize(ReferencedEnvelope srcEnvelope, SimpleFeatureCollection features) throws TransformException, FactoryException {
    final List<Map<String, Object>> buckets = readFeatures(features);

    final String firstGeohash = buckets.isEmpty() ? null : (String) buckets.get(0).get("key");
    final int precision;
    if (!isValid(firstGeohash)) {
        LOGGER.fine("No aggregations found or missing/invalid geohash key");
        precision = DEFAULT_PRECISION;
    } else {
        precision = ((String) buckets.get(0).get("key")).length();
    }

    cellWidth = GeoHash.widthDegrees(precision);
    cellHeight = GeoHash.heightDegrees(precision);

    if (srcEnvelope.getCoordinateReferenceSystem() != null) {
        srcEnvelope = srcEnvelope.transform(DefaultGeographicCRS.WGS84,false);
    }
    computeMinLonOffset(srcEnvelope);
    envelope = computeEnvelope(srcEnvelope, precision);

    boundingBox = new ReferencedEnvelope(envelope.getMinX()-cellWidth/2.0, envelope.getMaxX()+cellWidth/2.0,
            envelope.getMinY()-cellHeight/2.0, envelope.getMaxY()+cellHeight/2.0, DefaultGeographicCRS.WGS84);

    final int numCol = (int) Math.round((envelope.getMaxX()-envelope.getMinX())/cellWidth+1);
    final int numRow = (int) Math.round((envelope.getMaxY()-envelope.getMinY())/cellHeight+1);
    grid = new float[numRow][numCol];
    LOGGER.fine("Created grid with size (" + numCol + ", " + numRow + ")");

    if (emptyCellValue != 0) {
        for (float[] row: grid)
            Arrays.fill(row, emptyCellValue);
    }
    List<GridCell> cells = new ArrayList<>();
    buckets.forEach(bucket -> {
        Number rasterValue =  computeCellValue(bucket);
        cells.add(new GridCell((String) bucket.get("key"), rasterValue));
        scale.prepareScale(rasterValue.floatValue());
    });
    cells.forEach(cell -> updateGrid(cell.getGeohash(), cell.getValue()));
    LOGGER.fine("Read " + cells.size() + " aggregation buckets");
}
 
Example 11
Source File: NwwUtilities.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
public static ReferencedEnvelope readAndReprojectBounds( String path ) throws Exception {
    ReferencedEnvelope env = OmsVectorReader.readEnvelope(path);
    return env.transform(GPS_CRS, true);
}
 
Example 12
Source File: WebMapsController.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private void getFinalImage() {
        int imageWidth = Integer.parseInt(_outputWithField.getText());
        int imageHeight = Integer.parseInt(_outputHeightField.getText());

//            String filePath = _boundsFileField.getText();
        if (readEnvelope == null) {
            GuiUtilities.showWarningMessage(this, "A bounds file has to be loaded to export to geotiff.");
            return;
        }
        ReferencedEnvelope envelope = readEnvelope;

//            try {
//                if (filePath.endsWith(HMConstants.SUPPORTED_VECTOR_EXTENSIONS[0])) {
//                    envelope = OmsVectorReader.readEnvelope(filePath);
//                } else {
//                    GridCoverage2D raster = OmsRasterReader.readRaster(filePath);
//                    Polygon regionPolygon = CoverageUtilities.getRegionPolygon(raster);
//                    envelope = new ReferencedEnvelope(regionPolygon.getEnvelopeInternal(), raster.getCoordinateReferenceSystem());
//                }
//            } catch (Exception e2) {
//                e2.printStackTrace();
//                GuiUtilities.showErrorMessage(this, "Could not load bounds from file: " + e2.getLocalizedMessage());
//                return;
//            }

        try {

            String style = "";
            Object selectedStyleObj = _stylesCombo.getSelectedItem();
            if (selectedStyleObj != null) {
                style = selectedStyleObj.toString();
            }
            StyleImpl styleImpl = stylesMap.get(style);

            String selectedLayer = _layersCombo.getSelectedItem().toString();
            Layer layer = name2LayersMap.get(selectedLayer);

            String selectedFormat = _formatsCombo.getSelectedItem().toString();

            String epsg = _crsCombo.getSelectedItem().toString();
            CoordinateReferenceSystem crs = getCrs(epsg);

            ReferencedEnvelope env = envelope.transform(crs, true);

            GetMapRequest mapRequest = currentWms.getMapRequest(layer, selectedFormat, epsg, imageWidth, imageHeight, env, null,
                    styleImpl);
            GuiUtilities.copyToClipboard(currentWms.getUrl(mapRequest).toString());
            BufferedImage image = currentWms.getImage(mapRequest);
            if (image != null) {
                double xRes = env.getWidth() / imageWidth;
                double yRes = env.getHeight() / imageHeight;
                RegionMap envParams = CoverageUtilities.makeRegionParamsMap(env.getMaxY(), env.getMinY(), env.getMinX(),
                        env.getMaxX(), xRes, yRes, imageHeight, imageHeight);
                GridCoverage2D coverage = CoverageUtilities.buildCoverage("wms2tiff", image, envParams, crs);
                String outPath = _outputFileField.getText();
                OmsRasterWriter.writeRaster(outPath, coverage);

                CoverageUtilities.writeWorldFiles(coverage, outPath);

//                    ImageIO.write(image, "png", new File(outPath));

            } else {
                String message = currentWms.getMessage(mapRequest);
                if (message.contains("ServiceException")) {
                    final Pattern pattern = Pattern.compile("<ServiceException>(.+?)</ServiceException>", Pattern.DOTALL);
                    final Matcher matcher = pattern.matcher(message);
                    matcher.find();
                    message = matcher.group(1);
                    if (message != null) {
                        message = message.trim();
                        GuiUtilities.showWarningMessage(this, message);
                        return;
                    }
                }
                GuiUtilities.showWarningMessage(this, "Could not retrieve image for given parameters.");
            }

        } catch (Exception e1) {
            e1.printStackTrace();
            GuiUtilities.handleError(this, e1);
        }
    }