Java Code Examples for org.geotools.referencing.CRS#findMathTransform()

The following examples show how to use org.geotools.referencing.CRS#findMathTransform() . 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: SwtMapPane.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public void setCrs(final CoordinateReferenceSystem crs) {
	try {
		final ReferencedEnvelope rEnv = getDisplayArea();

		final CoordinateReferenceSystem sourceCRS = rEnv.getCoordinateReferenceSystem();
		final CoordinateReferenceSystem targetCRS = crs;

		final MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
		final com.vividsolutions.jts.geom.Envelope newJtsEnv = JTS.transform(rEnv, transform);

		final ReferencedEnvelope newEnvelope = new ReferencedEnvelope(newJtsEnv, targetCRS);
		content.getViewport().setBounds(newEnvelope);
		fullExtent = null;
		doSetDisplayArea(newEnvelope);

	} catch (final Exception e) {
		e.printStackTrace();
	}
}
 
Example 2
Source File: MBTilesHelper.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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: 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 4
Source File: GeoTools.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a mathematical transformation from the first given EPSG coordinate reference system into the second one. This method can be
 * used in conjunction with the {@link JTS#transform(Geometry, MathTransform)} method.
 *
 * @param fromCrsId the CRS identifier of the source coordinate reference system.
 * @param toCrsId the CRS identifier of the destination coordinate reference system.
 * @throws NullPointerException if any of the given EPSG identifier is null.
 * @throws NoSuchAuthorityCodeException if any of the given EPSG identifier is unknown.
 * @throws FactoryException if the requested coordinate reference system can't be created or the transformation or the coordinate failed.
 */
public static MathTransform mathTransform(final String fromCrsId, final String toCrsId)
    throws NullPointerException, NoSuchAuthorityCodeException, FactoryException {
  if (fromCrsId == null) {
    throw new NullPointerException("fromCrsId");
  }
  if (toCrsId == null) {
    throw new NullPointerException("toCrsId");
  }
  final String id = fromCrsId + ":" + toCrsId;
  if (transformCache.containsKey(id)) {
    return transformCache.get(id);
  }
  final CoordinateReferenceSystem fromCRS = crs(fromCrsId);
  final CoordinateReferenceSystem toCRS = crs(toCrsId);
  final MathTransform newTransform = CRS.findMathTransform(fromCRS, toCRS, true);
  final MathTransform existingTransform = transformCache.putIfAbsent(id, newTransform);
  if (existingTransform != null) {
    return existingTransform;
  }
  return newTransform;
}
 
Example 5
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 6
Source File: PolygonAreaCalculator.java    From geowave with Apache License 2.0 5 votes vote down vote up
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 7
Source File: FeatureDataAdapter.java    From geowave with Apache License 2.0 5 votes vote down vote up
private void initCRS(String indexCrsCode) {
  if ((indexCrsCode == null) || indexCrsCode.isEmpty()) {
    indexCrsCode = GeometryUtils.DEFAULT_CRS_STR;
  }
  CoordinateReferenceSystem persistedCRS = persistedFeatureType.getCoordinateReferenceSystem();

  if (persistedCRS == null) {
    persistedCRS = GeometryUtils.getDefaultCRS();
  }

  final CoordinateReferenceSystem indexCRS = decodeCRS(indexCrsCode);
  if (indexCRS.equals(persistedCRS)) {
    reprojectedFeatureType = SimpleFeatureTypeBuilder.retype(persistedFeatureType, persistedCRS);
    transform = null;
  } else {
    reprojectedFeatureType = SimpleFeatureTypeBuilder.retype(persistedFeatureType, indexCRS);
    try {
      transform = CRS.findMathTransform(persistedCRS, indexCRS, true);
      if (transform.isIdentity()) {
        transform = null;
      }
    } catch (final FactoryException e) {
      LOGGER.warn("Unable to create coordinate reference system transform", e);
    }
  }

  statsManager = new StatsManager(this, persistedFeatureType, reprojectedFeatureType, transform);
}
 
Example 8
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static GeometryCoordinateSequenceTransformer createTransformer(CoordinateReferenceSystem crs, CoordinateReferenceSystem modelCrs) {
    GeometryCoordinateSequenceTransformer transformer = new GeometryCoordinateSequenceTransformer();
    try {
        MathTransform reprojTransform = CRS.findMathTransform(crs, modelCrs, true);
        transformer.setMathTransform(reprojTransform);
        return transformer;
    } catch (FactoryException e) {
        throw new IllegalStateException("Could not create math transform", e);
    }
}
 
Example 9
Source File: ShowGeometryWktAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private Geometry transformGeometry(Geometry sourceGeom,
                                   CoordinateReferenceSystem sourceCrs,
                                   CoordinateReferenceSystem targetCrs) throws FactoryException, TransformException {
    MathTransform mt = CRS.findMathTransform(sourceCrs, targetCrs, true);
    GeometryCoordinateSequenceTransformer gcst = new GeometryCoordinateSequenceTransformer();
    gcst.setMathTransform(mt);
    return gcst.transform(sourceGeom);
}
 
Example 10
Source File: GeometryUtility.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Project geometry.
 *
 * @param originalGeom
 *            the original geom
 * @param srcCRSCode
 *            the src crs code
 * @param trgCRSCode
 *            the trg crs code
 * @return the geometry
 * @throws NoSuchAuthorityCodeException
 *             the no such authority code exception
 * @throws FactoryException
 *             the factory exception
 * @throws MismatchedDimensionException
 *             the mismatched dimension exception
 * @throws TransformException
 *             the transform exception
 */
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode,
    String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException,
    TransformException
{

    Geometry projectedGeometry = null;
    final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true);

    // converting geometries into a linear system
    try
    {
        projectedGeometry = JTS.transform(originalGeom, transform);
    }
    catch (Exception e)
    {
        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(
                    PrecisionModel.FLOATING), 4326);
        WKTReader reader = new WKTReader(geometryFactory);

        try
        {
            Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))");

            projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon),
                    transform);
        }
        catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }

    return projectedGeometry;
}
 
Example 11
Source File: TestVectorReprojector.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorReprojector() throws Exception {

        SimpleFeatureCollection testFC = HMTestMaps.getTestFC();

        OmsVectorReprojector reprojector = new OmsVectorReprojector();
        reprojector.inVector = testFC;
        reprojector.pCode = "EPSG:4326";
        reprojector.pm = pm;
        reprojector.process();

        CoordinateReferenceSystem sourceCRS = HMTestMaps.getCrs();
        CoordinateReferenceSystem targetCRS = CrsUtilities.getCrsFromSrid(4326);

        MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);

        SimpleFeatureCollection outFC = reprojector.outVector;
        FeatureIterator<SimpleFeature> featureIterator = outFC.features();
        SimpleFeatureIterator originalFeatureIterator = testFC.features();
        while( featureIterator.hasNext() ) {
            SimpleFeature feature = featureIterator.next();
            Geometry geometry = (Geometry) feature.getDefaultGeometry();
            Coordinate coordinate = geometry.getCoordinate();

            SimpleFeature originalFeature = originalFeatureIterator.next();
            Coordinate origCoord = ((Geometry) originalFeature.getDefaultGeometry()).getCoordinate();
            Coordinate reprojected = JTS.transform(origCoord, null, transform);

            assertEquals(reprojected.x, coordinate.x, delta);
            assertEquals(reprojected.y, coordinate.y, delta);
        }
        featureIterator.close();

    }
 
Example 12
Source File: PolygonAreaCalculator.java    From geowave with Apache License 2.0 5 votes vote down vote up
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 13
Source File: RasterUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static Geometry getFootprint(
    final ReferencedEnvelope projectedReferenceEnvelope,
    final GridCoverage gridCoverage) {
  try {
    final Envelope sampleEnvelope = gridCoverage.getEnvelope();
    final double avgSpan =
        (projectedReferenceEnvelope.getSpan(0) + projectedReferenceEnvelope.getSpan(1)) / 2;
    final MathTransform gridCrsToWorldCrs =
        CRS.findMathTransform(
            gridCoverage.getCoordinateReferenceSystem(),
            projectedReferenceEnvelope.getCoordinateReferenceSystem(),
            true);
    final Coordinate[] polyCoords =
        getWorldCoordinates(
            sampleEnvelope.getMinimum(0),
            sampleEnvelope.getMinimum(1),
            sampleEnvelope.getMaximum(0),
            sampleEnvelope.getMaximum(1),
            gridCrsToWorldCrs.isIdentity() ? 2
                : (int) Math.min(
                    Math.max((avgSpan * MIN_SEGMENTS) / SIMPLIFICATION_MAX_DEGREES, MIN_SEGMENTS),
                    MAX_SEGMENTS),
            gridCrsToWorldCrs);
    final Polygon poly = new GeometryFactory().createPolygon(polyCoords);
    if (polyCoords.length > MAX_VERTICES_BEFORE_SIMPLIFICATION) {
      final Geometry retVal = DouglasPeuckerSimplifier.simplify(poly, SIMPLIFICATION_MAX_DEGREES);
      if (retVal.isEmpty()) {
        return poly;
      }
      return retVal;
    } else {
      return poly;
    }
  } catch (MismatchedDimensionException | TransformException | FactoryException e1) {
    LOGGER.warn("Unable to calculate grid coverage footprint", e1);
  }
  return null;
}
 
Example 14
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private MathTransform getBaseMathTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	try {
		MathTransform transform;
		try {
			transform = CRS.findMathTransform(sourceCrs, targetCrs);
		} catch (Exception e) { // NOSONAR GeoTools can throw unexpected exceptions
			transform = CRS.findMathTransform(sourceCrs, targetCrs, true);
		}
		return transform;
	} catch (FactoryException fe) {
		throw new GeomajasException(fe, ExceptionCode.CRS_TRANSFORMATION_NOT_POSSIBLE, sourceCrs.getId(),
				targetCrs.getId());
	}
}
 
Example 15
Source File: Projection.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
MathTransform computeProjection(final IScope scope) {
	MathTransform crsTransformation = null;
	if (initialCRS == null) { return null; }
	try {
		crsTransformation = CRS.findMathTransform(initialCRS, getTargetCRS(scope), true);
	} catch (final FactoryException e) {
		e.printStackTrace();
		return null;
	}
	return crsTransformation;
}
 
Example 16
Source File: TestUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static MathTransform transformFromCrs(final CoordinateReferenceSystem crs) {
  MathTransform mathTransform = null;
  if (crs != null) {
    try {
      mathTransform = CRS.findMathTransform(GeometryUtils.getDefaultCRS(), crs, true);
    } catch (final FactoryException e) {
      LOGGER.warn("Unable to create coordinate reference system transform", e);
    }
  }
  return mathTransform;
}
 
Example 17
Source File: Wgs84Projection.java    From occurrence with Apache License 2.0 4 votes vote down vote up
/**
 * Reproject the given coordinates into WGS84 coordinates based on a known source datum or SRS.
 * Darwin Core allows not only geodetic datums but also full spatial reference systems as values for "datum".
 * The method will always return lat lons even if the processing failed. In that case only issues are set and the
 * parsing result set to fail - but with a valid payload.
 *
 * @param lat   the original latitude
 * @param lon   the original longitude
 * @param datum the original geodetic datum the coordinates are in
 *
 * @return the reprojected coordinates or the original ones in case transformation failed
 */
public static OccurrenceParseResult<LatLng> reproject(double lat, double lon, String datum) {
  Preconditions.checkArgument(lat >= -90d && lat <= 90d);
  Preconditions.checkArgument(lon >= -180d && lon <= 180d);

  Set<OccurrenceIssue> issues = EnumSet.noneOf(OccurrenceIssue.class);

  if (Strings.isNullOrEmpty(datum)) {
    issues.add(OccurrenceIssue.GEODETIC_DATUM_ASSUMED_WGS84);
    return OccurrenceParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new LatLng(lat, lon), issues);
  }

  try {
    CoordinateReferenceSystem crs = parseCRS(datum);
    if (crs == null) {
      issues.add(OccurrenceIssue.GEODETIC_DATUM_INVALID);
      issues.add(OccurrenceIssue.GEODETIC_DATUM_ASSUMED_WGS84);

    } else {
      MathTransform transform = CRS.findMathTransform(crs, DefaultGeographicCRS.WGS84, true);
      // different CRS may swap the x/y axis for lat lon, so check first:
      double[] srcPt;
      double[] dstPt = new double[3];
      if (CRS.getAxisOrder(crs) == CRS.AxisOrder.NORTH_EAST) {
        // lat lon
        srcPt = new double[] {lat, lon, 0};
      } else {
        // lon lat
        LOG.debug("Use lon/lat ordering for reprojection with datum={} and lat/lon={}/{}", datum, lat, lon);
        srcPt = new double[] {lon, lat, 0};
      }

      transform.transform(srcPt, 0, dstPt, 0, 1);

      double lat2 = dstPt[1];
      double lon2 = dstPt[0];
      // verify the datum shift is reasonable
      if (Math.abs(lat - lat2) > SUSPICIOUS_SHIFT || Math.abs(lon - lon2) > SUSPICIOUS_SHIFT) {
        issues.add(OccurrenceIssue.COORDINATE_REPROJECTION_SUSPICIOUS);
        LOG.debug("Found suspicious shift for datum={} and lat/lon={}/{} so returning failure and keeping orig coord",
          datum, lat, lon);
        return OccurrenceParseResult.fail(new LatLng(lat, lon), issues);
      }
      // flag the record if coords actually changed
      if (lat != lat2 || lon != lon2) {
        issues.add(OccurrenceIssue.COORDINATE_REPROJECTED);
      }
      return OccurrenceParseResult.success(ParseResult.CONFIDENCE.DEFINITE, new LatLng(lat2, lon2), issues);

    }
  } catch (Exception e) {
    issues.add(OccurrenceIssue.COORDINATE_REPROJECTION_FAILED);
    LOG.debug("Coordinate reprojection failed with datum={} and lat/lon={}/{}: {}", datum, lat, lon, e.getMessage());
  }

  return OccurrenceParseResult.fail(new LatLng(lat, lon), issues);
}
 
Example 18
Source File: GeotoolsDataStoreUtils.java    From TomboloDigitalConnector with MIT License 4 votes vote down vote up
public static MathTransform makeCrsTransform(String inputFormat) throws FactoryException {
    CoordinateReferenceSystem sourceCrs = CRS.decode(inputFormat);
    CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:"+Subject.SRID, true);

    return CRS.findMathTransform(sourceCrs, targetCrs);
}
 
Example 19
Source File: JGTProcessingRegion.java    From hortonmachine with GNU General Public License v3.0 3 votes vote down vote up
/**
 * 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 vote down vote up
/**
 * 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);
    }
}