Java Code Examples for org.geotools.geometry.jts.JTS#transform()
The following examples show how to use
org.geotools.geometry.jts.JTS#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: GeoServiceImpl.java From geomajas-project-server with GNU Affero General Public License v3.0 | 6 votes |
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "REC_CATCH_EXCEPTION") public Geometry transform(Geometry source, CrsTransform crsTransform) { try { if (crsTransform.isTransforming()) { Geometry transformableArea = crsTransform.getTransformableGeometry(); if (null != transformableArea && !transformableArea.covers(source)) { source = source.intersection(transformableArea); } return JTS.transform(source, crsTransform); } else { return source; } } catch (Exception e) { // NOSONAR typically TopologyException, TransformException or FactoryException logEnvelopeSuggestCrsTransformInfo(crsTransform.getId(), source, e); return createEmptyGeometryForClass(source.getClass()); } }
Example 2
Source File: MBTilesHelper.java From hortonmachine with GNU General Public License v3.0 | 6 votes |
/** * Read the image of a tile from a generic geotools coverage reader. * * @param reader the reader, expected to be in CRS 3857. * @param x the tile x. * @param y the tile y. * @param zoom the zoomlevel. * @return the image. * @throws IOException */ public static BufferedImage readGridcoverageImageForTile( AbstractGridCoverage2DReader reader, int x, int y, int zoom, CoordinateReferenceSystem resampleCrs ) throws IOException { double north = tile2lat(y, zoom); double south = tile2lat(y + 1, zoom); double west = tile2lon(x, zoom); double east = tile2lon(x + 1, zoom); Coordinate ll = new Coordinate(west, south); Coordinate ur = new Coordinate(east, north); try { CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84; MathTransform transform = CRS.findMathTransform(sourceCRS, resampleCrs); ll = JTS.transform(ll, null, transform); ur = JTS.transform(ur, null, transform); } catch (Exception e) { e.printStackTrace(); } BufferedImage image = ImageUtilities.imageFromReader(reader, TILESIZE, TILESIZE, ll.x, ur.x, ll.y, ur.y, resampleCrs); return image; }
Example 3
Source File: RasterizedSpatialiteLasLayer.java From hortonmachine with GNU General Public License v3.0 | 6 votes |
private static void drawCells( ASpatialDb db, ColorInterpolator colorInterp, PointTransformation pointTransformation, Geometry polygon, Graphics2D gr, MathTransform data2NwwTransform, boolean doIntensity, int finalTileSize ) throws Exception { int maxPerImage = 100000; List<LasCell> lasCells = LasCellsTable.getLasCells(db, null, polygon, true, true, false, false, false, maxPerImage); int size = lasCells.size(); if (size > 0) { int jump = size / maxPerImage; for( int i = 0; i < size; i = i + 1 + jump ) { LasCell lasCell = lasCells.get(i); if (lasCell.pointsCount == 0) { continue; } Polygon levelPolygon = lasCell.polygon; Geometry polygonNww = JTS.transform(levelPolygon, data2NwwTransform); GeneralPath p = polygonToPath(pointTransformation, polygonNww, finalTileSize); Color c = colorInterp.getColorFor(doIntensity ? lasCell.avgIntensity : lasCell.avgElev); gr.setPaint(c); gr.fill(p); } } }
Example 4
Source File: RL2NwwLayer.java From hortonmachine with GNU General Public License v3.0 | 6 votes |
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 5
Source File: AbstractGeotoolsDataStoreImporter.java From TomboloDigitalConnector with MIT License | 5 votes |
private Optional<Geometry> extractNormalizedGeometry(SimpleFeature feature, MathTransform crsTransform) throws TransformException { try { Geometry geom = (Geometry) feature.getDefaultGeometry(); Geometry transformedGeom = JTS.transform(geom, crsTransform); transformedGeom.setSRID(Subject.SRID); return Optional.of(transformedGeom); } catch (ProjectionException e) { log.warn("Rejecting feature {}. You will see this if you have assertions enabled (e.g. " + "you run with `-ea`) as GeoTools runs asserts. See source of GeotoolsDataStoreUtils for details on this. " + "To fix this, replace `-ea` with `-ea -da:org.geotools...` in your test VM options (probably in" + "your IDE) to disable assertions in GeoTools.", feature.getID()); return Optional.empty(); } }
Example 6
Source File: PolygonAreaCalculator.java From geowave with Apache License 2.0 | 5 votes |
public double getAreaDensify(final Geometry polygon) throws Exception { final Point centroid = polygon.getCentroid(); final CoordinateReferenceSystem equalAreaCRS = lookupUtmCrs(centroid.getY(), centroid.getX()); final double vertexSpacing = polygon.getLength() / densifyVertexCount; final Geometry densePolygon = Densifier.densify(polygon, vertexSpacing); final MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, equalAreaCRS, true); final Geometry transformedPolygon = JTS.transform(densePolygon, transform); return transformedPolygon.getArea() * SQM_2_SQKM; }
Example 7
Source File: PolygonAreaCalculator.java From geowave with Apache License 2.0 | 5 votes |
public double getAreaSimple(final Geometry polygon) throws Exception { final Point centroid = polygon.getCentroid(); final CoordinateReferenceSystem equalAreaCRS = lookupUtmCrs(centroid.getY(), centroid.getX()); final MathTransform transform = CRS.findMathTransform(DefaultGeographicCRS.WGS84, equalAreaCRS, true); final Geometry transformedPolygon = JTS.transform(polygon, transform); return transformedPolygon.getArea() * SQM_2_SQKM; }
Example 8
Source File: GeoUtils.java From gtfs-validator with MIT License | 5 votes |
public static Coordinate convertToLonLat( MathTransform transform, Coordinate xy) { final Coordinate to = new Coordinate(); final Coordinate yx = new Coordinate(xy.y, xy.x); try { JTS.transform(yx, to, transform.inverse()); } catch (final TransformException e) { e.printStackTrace(); } return new Coordinate(to.y, to.x); }
Example 9
Source File: GeoUtils.java From collect-earth with MIT License | 5 votes |
public static Point transformToWGS84(double longitude, double latitude, String sourceEpsgCode ) throws TransformException, FactoryException { final GeometryFactory gf = new GeometryFactory(); final Coordinate c = new Coordinate(longitude, latitude); Point p = gf.createPoint(c); final CoordinateReferenceSystem sourceEpsgCRS = CRS.decode(sourceEpsgCode); final MathTransform mathTransform = CRS.findMathTransform(sourceEpsgCRS, DefaultGeographicCRS.WGS84, false); return (Point) JTS.transform(p, mathTransform); }
Example 10
Source File: VectorCrsConversionTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
private void verify(Coordinate mercator, Coordinate lonlat, double x, double y, double lon, double lat) throws Exception { Coordinate projected = new Coordinate(); projected = JTS.transform(mercator, projected, layerToMap); Assert.assertEquals(x, mercator.x, TOLERANCE); Assert.assertEquals(lon, projected.x, TOLERANCE); Assert.assertEquals(lon, lonlat.x, TOLERANCE); Assert.assertEquals(y, mercator.y, TOLERANCE); Assert.assertEquals(lat, projected.y, TOLERANCE); Assert.assertEquals(lat, lonlat.y, TOLERANCE); }
Example 11
Source File: ExtractGeometryFilterVisitor.java From geowave with Apache License 2.0 | 5 votes |
@Override public Object visit(final BBOX filter, final Object data) { if (attributeOfInterest.equals(filter.getExpression1().toString())) { final Geometry bbox = bbox(data); final BoundingBox referencedBBox = filter.getBounds(); Geometry bounds = new GeometryFactory().toGeometry( new Envelope( referencedBBox.getMinX(), referencedBBox.getMaxX(), referencedBBox.getMinY(), referencedBBox.getMaxY())); if ((crs != null) && (referencedBBox.getCoordinateReferenceSystem() != null) && !crs.equals(referencedBBox.getCoordinateReferenceSystem())) { try { bounds = JTS.transform( bounds, CRS.findMathTransform(referencedBBox.getCoordinateReferenceSystem(), crs, true)); } catch (MismatchedDimensionException | TransformException | FactoryException e) { LOGGER.error("Unable to transforma bbox", e); } } if (bbox != null) { return bbox.union(bounds); } else { return new ExtractGeometryFilterVisitorResult(bounds, CompareOperation.INTERSECTS); } } else { return new ExtractGeometryFilterVisitorResult(infinity(), null); } }
Example 12
Source File: GrassLegacyUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
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 13
Source File: CoverageUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Utility method for transforming a geometry ROI into the raster space, using the provided affine transformation. * * @param roi a {@link Geometry} in model space. * @param mt2d an {@link AffineTransform} that maps from raster to model space. This is already referred to the pixel corner. * @return a {@link ROI} suitable for using with JAI. * @throws ProcessException in case there are problems with ivnerting the provided {@link AffineTransform}. Very unlikely to happen. */ public static ROI prepareROI( Geometry roi, AffineTransform mt2d ) throws Exception { // transform the geometry to raster space so that we can use it as a ROI source Geometry rasterSpaceGeometry = JTS.transform(roi, new AffineTransform2D(mt2d.createInverse())); // simplify the geometry so that it's as precise as the coverage, excess coordinates // just make it slower to determine the point in polygon relationship Geometry simplifiedGeometry = DouglasPeuckerSimplifier.simplify(rasterSpaceGeometry, 1); // build a shape using a fast point in polygon wrapper return new ROIShape(new FastLiteShape(simplifiedGeometry)); }
Example 14
Source File: TiledRasterLayerService.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
private Coordinate getTileIndicesFromMap(CrsTransform mapToLayer, Coordinate centerMapCoor, int zoomLevel) throws TransformException { Coordinate centerLayerCoor = JTS.transform(centerMapCoor, new Coordinate(), mapToLayer); double xIndex = (centerLayerCoor.x + HALF_EQUATOR_IN_METERS) * POWERS_OF_TWO[zoomLevel] / EQUATOR_IN_METERS; double yIndex = (-centerLayerCoor.y + HALF_EQUATOR_IN_METERS) * POWERS_OF_TWO[zoomLevel] / EQUATOR_IN_METERS; return new Coordinate(xIndex, yIndex); }
Example 15
Source File: GoogleLayer.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
private int getBestZoomLevelForScaleInPixPerMeter(CrsTransform layerToGoogle, Coordinate mapPosition, double scale) { double scaleRatio = MAP_UNIT_PER_GOOGLE_METER_DEFAULT; try { Coordinate mercatorCenter = JTS.transform(mapPosition, new Coordinate(), layerToGoogle); Coordinate dx = JTS.transform(new Coordinate(mapPosition.x + 1, mapPosition.y), new Coordinate(), layerToGoogle); scaleRatio = 1.0 / (dx.x - mercatorCenter.x); } catch (TransformException e) { log.warn("calculateMapUnitPerGoogleMeter() : transformation failed", e); } double scaleInPixPerMeter = scale * scaleRatio; double screenResolution = 1.0 / scaleInPixPerMeter; if (screenResolution >= resolutions[0]) { return 0; } else if (screenResolution <= resolutions[maxZoomlevel]) { return maxZoomlevel; } else { for (int i = 0; i < maxZoomlevel; i++) { double upper = resolutions[i]; double lower = resolutions[i + 1]; if (screenResolution <= upper && screenResolution >= lower) { if ((upper - screenResolution) > 2 * (screenResolution - lower)) { return i + 1; } else { return i; } } } } // should not occur !!!! return maxZoomlevel; }
Example 16
Source File: OpenMappingImporter.java From TomboloDigitalConnector with MIT License | 5 votes |
public Geometry getShape(String wtk) throws FactoryException, TransformException { GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), Subject.SRID); WKTReader reader = new WKTReader(geometryFactory); MathTransform crsTransform = GeotoolsDataStoreUtils.makeCrsTransform("EPSG:27700"); try { LineString line = (LineString) reader.read(wtk); Geometry transformedGeom = JTS.transform(line, crsTransform); return transformedGeom; } catch (ParseException e) { e.printStackTrace(); log.error("Not a valid geometry"); return null; } }
Example 17
Source File: GoogleLayer.java From geomajas-project-server with GNU Affero General Public License v3.0 | 4 votes |
@Override public List<RasterTile> paint(CoordinateReferenceSystem targetCrs, Envelope bounds, double scale) throws GeomajasException { if (isTilesEnabled()) { try { CrsTransform layerToMap = geoService.getCrsTransform(crs, targetCrs); CrsTransform mapToLayer = geoService.getCrsTransform(targetCrs, crs); CrsTransform layerToWsg84 = geoService.getCrsTransform(crs, geoService.getCrs2(WSG_84)); // find the center of the map in map coordinates (positive y-axis) Coordinate boundsCenter = new Coordinate((bounds.getMinX() + bounds.getMaxX()) / 2, (bounds.getMinY() + bounds.getMaxY()) / 2); // Translate the map coordinates to layer coordinates, assumes equal x-y orientation Envelope layerBounds = geoService.transform(bounds, mapToLayer); // double layerScale = bounds.getWidth() * scale / layerBounds.getWidth(); layerBounds = clipBounds(layerBounds); if (layerBounds.isNull()) { return new ArrayList<RasterTile>(0); } // find zoomlevel // scale in pix/m should just above the given scale so we have at least one // screen pixel per google pixel ! (otherwise text unreadable) int zoomLevel = getBestZoomLevelForScaleInPixPerMeter(mapToLayer, boundsCenter, scale); log.debug("zoomLevel={}", zoomLevel); RasterGrid grid = getRasterGrid(layerBounds, tileSize * resolutions[zoomLevel], tileSize * resolutions[zoomLevel]); // We calculate the first tile's screen box with this assumption List<RasterTile> result = new ArrayList<RasterTile>(); for (int i = grid.getXmin(); i < grid.getXmax(); i++) { for (int j = grid.getYmin(); j < grid.getYmax(); j++) { double x = grid.getLowerLeft().x + (i - grid.getXmin()) * grid.getTileWidth(); double y = grid.getLowerLeft().y + (j - grid.getYmin()) * grid.getTileHeight(); // layer coordinates Bbox worldBox; Bbox layerBox; layerBox = new Bbox(x, y, grid.getTileWidth(), grid.getTileHeight()); // Transforming back to map coordinates will only result in a proper grid if the transformation // is nearly affine worldBox = geoService.transform(layerBox, layerToMap); // Rounding to avoid white space between raster tiles lower-left becomes upper-left in inverted // y-space Bbox screenBox = new Bbox(Math.round(scale * worldBox.getX()), -Math.round(scale * worldBox.getMaxY()), Math.round(scale * worldBox.getMaxX()) - Math.round(scale * worldBox.getX()), Math.round(scale * worldBox.getMaxY()) - Math.round(scale * worldBox.getY())); RasterTile image = new RasterTile(screenBox, getId() + "." + zoomLevel + "." + i + "," + j); String url = tileUrl; Coordinate center = new Coordinate((layerBox.getX() + layerBox.getMaxX()) / 2, (layerBox.getY() + layerBox.getMaxY()) / 2); Coordinate centerInWsg84 = JTS.transform(center, new Coordinate(), layerToWsg84); url = url.replace("${center}", Double.toString(centerInWsg84.y) + "," + Double.toString(centerInWsg84.x)); url = url.replace("${level}", Integer.toString(zoomLevel)); // When we are trying to display the tiles on a different coordinate system, use double scaled // images so that renderings are more smooth. This will return an image tileSize*2 x tileSize*2. // Disabled becausd the printing plugin can't handle this! // if (!layerToMap.isIdentity()) { // url += "&scale=2"; // } image.setCode(new TileCode(zoomLevel, i, j)); image.setUrl(url); log.debug("adding image {}", image); result.add(image); } } return result; } catch (TransformException e) { throw new GeomajasException(e, ExceptionCode.RENDER_TRANSFORMATION_FAILED); } } else { return Collections.emptyList(); } }
Example 18
Source File: TiledRasterLayerService.java From geomajas-project-server with GNU Affero General Public License v3.0 | 4 votes |
private Coordinate getMapFromTileIndices(CrsTransform mapToLayer, Coordinate indices, int zoomLevel) throws TransformException { double xMeter = EQUATOR_IN_METERS * indices.x / POWERS_OF_TWO[zoomLevel] - HALF_EQUATOR_IN_METERS; double yMeter = -EQUATOR_IN_METERS * indices.y / POWERS_OF_TWO[zoomLevel] + HALF_EQUATOR_IN_METERS; return JTS.transform(new Coordinate(xMeter, yMeter), new Coordinate(), mapToLayer); }
Example 19
Source File: JGTProcessingRegion.java From hortonmachine with GNU General Public License v3.0 | 3 votes |
/** * Reprojects a {@link JGTProcessingRegion region}. * * @param sourceCRS * the original {@link CoordinateReferenceSystem crs} of the * region. * @param targetCRS * the target {@link CoordinateReferenceSystem crs} of the * region. * @param lenient * defines whether to apply a lenient transformation or not. * @return a new {@link JGTProcessingRegion region}. * @throws Exception * exception that may be thrown when applying the * transformation. */ public JGTProcessingRegion reproject( CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS, boolean lenient ) throws Exception { MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS, lenient); Envelope envelope = getEnvelope(); Envelope targetEnvelope = JTS.transform(envelope, transform); return new JGTProcessingRegion(targetEnvelope.getMinX(), targetEnvelope.getMaxX(), targetEnvelope.getMinY(), targetEnvelope.getMaxY(), getRows(), getCols()); }
Example 20
Source File: CrsUtilities.java From hortonmachine with GNU General Public License v3.0 | 3 votes |
/** * Reproject a set of coordinates. * * @param from the starting crs * @param to the destination crs * @param coordinates the array of coordinates, wrapped into an Object array * * @throws Exception */ public static void reproject( CoordinateReferenceSystem from, CoordinateReferenceSystem to, Coordinate[] coordinates ) throws Exception { MathTransform mathTransform = CRS.findMathTransform(from, to); for( int i = 0; i < coordinates.length; i++ ) { coordinates[i] = JTS.transform(coordinates[i], coordinates[i], mathTransform); } }