Java Code Examples for org.opengis.referencing.operation.TransformException

The following are top voted examples for showing how to use org.opengis.referencing.operation.TransformException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: downloadclient   File: WMSMapSwing.java   View source code 8 votes vote down vote up
/**
 * sets the viewport of the map to the given extend.
 *
 * @param envelope the extend
 */
public void setExtend(ReferencedEnvelope envelope) {
    try {
        envelope = envelope.transform(this.mapContent.getViewport()
                .getCoordinateReferenceSystem(), true);
        double xLength = envelope.getSpan(0);
        xLength = xLength * TEN_PERCENT;
        double yLength = envelope.getSpan(1);
        yLength = yLength * TEN_PERCENT;
        envelope.expandBy(xLength, yLength);
        bboxAction.resetCoordinates();
        mapPane.deleteGraphics();
        mapPane.setDisplayArea(envelope);
    } catch (FactoryException | TransformException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}
 
Example 2
Project: chordatlas   File: SatUtils.java   View source code 6 votes vote down vote up
public static Point2d worldToLLong( Tweed tweed, Point3d cen ) {

		Point3d out = new Point3d( cen );
		TweedSettings.settings.fromOrigin.transform( out );

		try {
			double[] latLong = new double[3];

			toLatLong.transform( new double[] { out.x, out.y, out.z }, 0, latLong, 0, 1 );

			return new Point2d( latLong[ 0 ], latLong[ 1 ] );
		} catch ( TransformException e ) {
			e.printStackTrace();
		}
		return null;
	}
 
Example 3
Project: ms-gs-plugins   File: BoundsUpdateTransactionListener.java   View source code 6 votes vote down vote up
private Optional<ReferencedEnvelope> merge(final ReferencedEnvelope oldEnv,
        final Collection<ReferencedEnvelope> dirtyList) {
    final CoordinateReferenceSystem declaredCrs = oldEnv.getCoordinateReferenceSystem();
    return dirtyList.stream()
        .map(env->{
            if(env instanceof ReferencedEnvelope3D) {
                return new ReferencedEnvelope(env, CRS.getHorizontalCRS(env.getCoordinateReferenceSystem()));
            } else  {
                return env;
            }
        })
        .map(env->{
            try {
                return env.transform(declaredCrs, true, 1000);
            } catch (TransformException | FactoryException e) {
                throw new RuntimeException("Error while merging bounding boxes",e);
            }
        })
        .reduce((env1, env2)->{ReferencedEnvelope x = new ReferencedEnvelope(env1); x.expandToInclude(env2); return x;});
}
 
Example 4
Project: downloadclient   File: WMSMapSwing.java   View source code 6 votes vote down vote up
private void setDisplayCoordinates(
        Double x1,
        Double y1,
        Double x2,
        Double y2
) {
    try {
        convertAndDisplayBoundingBox(x1,
                x2,
                y1,
                y2,
                this.mapCRS,
                this.displayCRS);
    } catch (FactoryException | TransformException e) {
        clearCoordinateDisplay();
        log.log(Level.SEVERE, e.getMessage(), e);
    }
}
 
Example 5
Project: online-whatif   File: GeodataFilterer.java   View source code 6 votes vote down vote up
/**
 * Gets the filter from parameters.
 *
 * @param wifParameters
 *          the wif parameters
 * @return the filter from parameters
 * @throws MismatchedDimensionException
 *           the mismatched dimension exception
 * @throws TransformException
 *           the transform exception
 * @throws NoSuchAuthorityCodeException
 *           the no such authority code exception
 * @throws FactoryException
 *           the factory exception
 * @throws ParseException
 *           the parse exception
 * @throws CQLException
 *           the cQL exception
 */
public Filter getFilterFromParameters(final Map<String, Object> wifParameters)
    throws MismatchedDimensionException, TransformException,
    NoSuchAuthorityCodeException, FactoryException, ParseException,
    CQLException {
  LOGGER.debug("getFilterFromParameters...");

  String queryTxt = "";

  final String polyTxt = getIntersectionPolygon(wifParameters);

  if (polyTxt == null) {
    LOGGER
    .info("no polygon query filter received, defaulting to including all the unified area zone!");
    queryTxt = "include";
  } else if (polyTxt.equals("")) {
    LOGGER
    .info("no polygon query filter received, defaulting to including all the unified area zone!");
    queryTxt = "include";
  } else {
    queryTxt = polyTxt;
  }
  LOGGER.debug("query filter: {}", queryTxt);
  return getFilter(queryTxt);
}
 
Example 6
Project: gtfs-lib   File: GeoUtils.java   View source code 6 votes vote down vote up
@Deprecated
public static ProjectedCoordinate convertLonLatToEuclidean(
  Coordinate lonlat) {

  final MathTransform transform = getTransform(lonlat);
  final Coordinate to = new Coordinate();

  // the transform seems to swap the lat lon pairs
  Coordinate latlon = new Coordinate(lonlat.y, lonlat.x);

  try {
    JTS.transform(latlon, to,
        transform);
  } catch (final TransformException e) {
    e.printStackTrace();
  }

  return new ProjectedCoordinate(transform, new Coordinate(to.y, to.x), lonlat);
}
 
Example 7
Project: s3tbx-c2rcc   File: MsiProductSignatureTest.java   View source code 6 votes vote down vote up
@Test
public void testProductSignature_DefaultWithOthers() throws FactoryException, TransformException {

    C2rccMsiOperator operator = createDefaultOperator();
    operator.setOutputRpath(true);
    operator.setOutputTdown(true);
    operator.setOutputTup(true);
    operator.setOutputOos(true);
    Product targetProduct = operator.getTargetProduct();

    assertDefaults(targetProduct, false);
    assertBands(targetProduct, EXPECTED_RPATH_BANDS);
    assertBands(targetProduct, EXPECTED_TDOWN_BANDS);
    assertBands(targetProduct, EXPECTED_TUP_BANDS);
    assertBands(targetProduct, EXPECTED_OOS_RTOSA);
    assertBands(targetProduct, EXPECTED_OOS_RHOW);
}
 
Example 8
Project: s3tbx-c2rcc   File: MsiProductSignatureTest.java   View source code 6 votes vote down vote up
private Product createMsiTestProduct() throws FactoryException, TransformException {
    Product product = new Product("test-msi", "t", 1, 1);
    for (String reflBandName : C2rccMsiAlgorithm.SOURCE_BAND_REFL_NAMES) {
        product.addBand(reflBandName, "3863");
    }

    product.addBand(C2rccMsiOperator.RASTER_NAME_SUN_AZIMUTH, "42");
    product.addBand(C2rccMsiOperator.RASTER_NAME_SUN_ZENITH, "42");
    product.addBand(C2rccMsiOperator.RASTER_NAME_VIEW_AZIMUTH, "42");
    product.addBand(C2rccMsiOperator.RASTER_NAME_VIEW_ZENITH, "42");

    product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 1, 1, 10, 50, 1, 1));

    MetadataElement l1cUserProduct = new MetadataElement("Level-1C_User_Product");
    MetadataElement generalInfo = new MetadataElement("General_Info");
    MetadataElement productInfo = new MetadataElement("Product_Info");
    productInfo.addAttribute(new MetadataAttribute("PRODUCT_START_TIME", ProductData.createInstance("2015-08-12T10:40:21.459Z"), true));
    productInfo.addAttribute(new MetadataAttribute("PRODUCT_STOP_TIME", ProductData.createInstance("2015-08-12T10:40:21.459Z"), true));
    MetadataElement imageCharacteristics = new MetadataElement("Product_Image_Characteristics");
    imageCharacteristics.addAttribute(new MetadataAttribute("QUANTIFICATION_VALUE", ProductData.createInstance("1000"), true));
    l1cUserProduct.addElement(generalInfo);
    generalInfo.addElement(productInfo);
    generalInfo.addElement(imageCharacteristics);
    product.getMetadataRoot().addElement(l1cUserProduct);
    return product;
}
 
Example 9
Project: s3tbx-c2rcc   File: Meris4ProductSignatureTest.java   View source code 6 votes vote down vote up
@Test
public void testProductSignature_DefaultWithOthers() throws FactoryException, TransformException {

    C2rccMeris4Operator operator = createDefaultOperator();
    operator.setOutputRpath(true);
    operator.setOutputTdown(true);
    operator.setOutputTup(true);
    operator.setOutputOos(true);
    Product targetProduct = operator.getTargetProduct();

    assertDefaults(targetProduct, false);
    assertBands(targetProduct, EXPECTED_RPATH_BANDS);
    assertBands(targetProduct, EXPECTED_TDOWN_BANDS);
    assertBands(targetProduct, EXPECTED_TUP_BANDS);
    assertBands(targetProduct, EXPECTED_OOS_RTOSA);
    assertBands(targetProduct, EXPECTED_OOS_RHOW);
}
 
Example 10
Project: s3tbx-c2rcc   File: OlciProductSignatureTest.java   View source code 6 votes vote down vote up
@Test
public void testProductSignature_DefaultWithOthers() throws FactoryException, TransformException {

    C2rccOlciOperator operator = createDefaultOperator();
    operator.setOutputRpath(true);
    operator.setOutputTdown(true);
    operator.setOutputTup(true);
    operator.setOutputOos(true);
    Product targetProduct = operator.getTargetProduct();

    assertDefaults(targetProduct, false);
    assertBands(targetProduct, EXPECTED_RPATH_BANDS);
    assertBands(targetProduct, EXPECTED_TDOWN_BANDS);
    assertBands(targetProduct, EXPECTED_TUP_BANDS);
    assertBands(targetProduct, EXPECTED_OOS_RTOSA);
    assertBands(targetProduct, EXPECTED_OOS_RHOW);
}
 
Example 11
Project: s3tbx-c2rcc   File: ModisProductSignatureTest.java   View source code 6 votes vote down vote up
private Product createModisTestProduct() throws FactoryException, TransformException {
    Product product = new Product("test-modis", "t", 1, 1);
    int[] reflecWavelengths = C2rccModisAlgorithm.ALL_REFLEC_WAVELENGTHS;
    for (int reflec_wavelength : reflecWavelengths) {
        String expression = String.valueOf(reflec_wavelength);
        product.addBand(C2rccModisOperator.SOURCE_RADIANCE_NAME_PREFIX + reflec_wavelength, expression);
    }

    Date time = new Date();
    product.setStartTime(ProductData.UTC.create(time, 0));
    product.setEndTime(ProductData.UTC.create(time, 500));

    for (String angleName : C2rccModisOperator.GEOMETRY_ANGLE_NAMES) {
        product.addBand(angleName, "42");
    }

    Band flagBand = product.addBand(C2rccModisOperator.RASTER_NAME_L2_FLAGS, ProductData.TYPE_INT8);
    FlagCoding l2FlagsCoding = new FlagCoding(C2rccModisOperator.RASTER_NAME_L2_FLAGS);
    l2FlagsCoding.addFlag("LAND", 0x01, "");
    product.getFlagCodingGroup().add(l2FlagsCoding);
    flagBand.setSampleCoding(l2FlagsCoding);

    product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 1, 1, 10, 50, 1, 1));

    return product;
}
 
Example 12
Project: s3tbx-c2rcc   File: SeawifsProductSignatureTest.java   View source code 6 votes vote down vote up
private Product createSeawifsTestProduct() throws FactoryException, TransformException {
    Product product = new Product("test-seawifs", "t", 1, 1);
    int[] reflecWavelengths = C2rccSeaWiFSAlgorithm.seawifsWavelengths;
    for (int reflec_wavelength : reflecWavelengths) {
        String expression = String.valueOf(reflec_wavelength);
        product.addBand(C2rccSeaWiFSOperator.SOURCE_RADIANCE_NAME_PREFIX + reflec_wavelength, expression);
    }

    Date time = new Date();
    product.setStartTime(ProductData.UTC.create(time, 0));
    product.setEndTime(ProductData.UTC.create(time, 500));

    for (String angleName : C2rccSeaWiFSOperator.GEOMETRY_ANGLE_NAMES) {
        product.addBand(angleName, "42");
    }

    Band flagBand = product.addBand(C2rccSeaWiFSOperator.RASTER_NAME_L2_FLAGS, ProductData.TYPE_INT8);
    FlagCoding l2FlagsCoding = new FlagCoding(C2rccSeaWiFSOperator.RASTER_NAME_L2_FLAGS);
    l2FlagsCoding.addFlag("LAND", 0x01, "");
    product.getFlagCodingGroup().add(l2FlagsCoding);
    flagBand.setSampleCoding(l2FlagsCoding);

    product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 1, 1, 10, 50, 1, 1));

    return product;
}
 
Example 13
Project: s3tbx-c2rcc   File: Landsat8ProductSignatureTest.java   View source code 6 votes vote down vote up
@Test
public void testProductSignature_DefaultWithOthers() throws FactoryException, TransformException {

    C2rccLandsat8Operator operator = createDefaultOperator();
    operator.setOutputRpath(true);
    operator.setOutputTdown(true);
    operator.setOutputTup(true);
    operator.setOutputOos(true);
    Product targetProduct = operator.getTargetProduct();

    assertDefaults(targetProduct, false);
    assertBands(targetProduct, EXPECTED_RPATH_BANDS);
    assertBands(targetProduct, EXPECTED_TDOWN_BANDS);
    assertBands(targetProduct, EXPECTED_TUP_BANDS);
    assertBands(targetProduct, EXPECTED_OOS_RTOSA);
    assertBands(targetProduct, EXPECTED_OOS_RHOW);
}
 
Example 14
Project: elasticgeo   File: GeoHashGridProcessTest.java   View source code 6 votes vote down vote up
@Test
public void testSubCellCrop() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-168.75,168.75,-78.75,78.75,DefaultGeographicCRS.WGS84);
    int width = 16;
    int height = 8;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 15
Project: s3tbx-c2rcc   File: ViirsProductSignatureTest.java   View source code 6 votes vote down vote up
private Product createSeawifsTestProduct() throws FactoryException, TransformException {
    Product product = new Product("test-seawifs", "t", 1, 1);
    int[] reflecWavelengths = C2rccViirsAlgorithm.viirsWavelengths;
    for (int reflec_wavelength : reflecWavelengths) {
        String expression = String.valueOf(reflec_wavelength);
        product.addBand(C2rccViirsOperator.SOURCE_RADIANCE_NAME_PREFIX + reflec_wavelength, expression);
    }

    Date time = new Date();
    product.setStartTime(ProductData.UTC.create(time, 0));
    product.setEndTime(ProductData.UTC.create(time, 500));

    for (String angleName : C2rccViirsOperator.GEOMETRY_ANGLE_NAMES) {
        product.addBand(angleName, "42");
    }

    Band flagBand = product.addBand(C2rccViirsOperator.RASTER_NAME_L2_FLAGS, ProductData.TYPE_INT8);
    FlagCoding l2FlagsCoding = new FlagCoding(C2rccViirsOperator.RASTER_NAME_L2_FLAGS);
    l2FlagsCoding.addFlag("LAND", 0x01, "");
    product.getFlagCodingGroup().add(l2FlagsCoding);
    flagBand.setSampleCoding(l2FlagsCoding);

    product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 1, 1, 10, 50, 1, 1));

    return product;
}
 
Example 16
Project: gama   File: Projection.java   View source code 6 votes vote down vote up
@Override
public Geometry transform(final Geometry g) {
	// Remove uselessly complicated multigeometries
	if (g instanceof GeometryCollection && g.getNumGeometries() == 1) { return transform(g.getGeometryN(0)); }
	Geometry geom = GeometryUtils.GEOMETRY_FACTORY.createGeometry(g);
	if (transformer != null) {
		try {
			geom = transformer.transform(geom);
		} catch (final TransformException e) {
			e.printStackTrace();
		}
	}
	translate(geom);
	convertUnit(geom);
	return geom;
}
 
Example 17
Project: elasticgeo   File: GeoHashGridProcessTest.java   View source code 6 votes vote down vote up
@Test
public void testBasic() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    int width = 8;
    int height = 4;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 18
Project: elasticgeo   File: GeoHashGridProcessTest.java   View source code 6 votes vote down vote up
@Test
public void testScaled() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    int width = 16;
    int height = 8;
    int pixelsPerCell = 1;
    String strategy = "Basic";
    List<String> strategyArgs = null;
    Float emptyCellValue = null;
    Float scaleMin = 0f;
    Float scaleMax = null;
    boolean useLog = false;

    GridCoverage2D coverage = process.execute(features, pixelsPerCell, strategy, strategyArgs, emptyCellValue, scaleMin, scaleMax, useLog, envelope, width, height, null);
    checkInternal(coverage, fineDelta);
    checkEdge(coverage, envelope, fineDelta);
}
 
Example 19
Project: sumo   File: TerrasarXImage_SLC.java   View source code 5 votes vote down vote up
@Override
public boolean initialise() {
	try {
		this.displayName=manifestFile.getName();
		setFile(manifestFile);
    	
    	parseProductXML(productxml);
    	
    	tiffImages = getImages();
    	//TIFF image = tiffImages.values().iterator().next();
        bounds = new Rectangle(0, 0, getMetaWidth(),getMetaHeight());
        
        gcps = getGcps();
        if (gcps == null) {
            dispose();
            return false;
        }
        //get satellite altitude
        geotransform = GeoTransformFactory.createFromGcps(gcps, "EPSG:4326");
        double radialdist = Math.pow(xposition * xposition + yposition * yposition + zposition * zposition, 0.5);
        MathTransform convert;
        double[] latlon = getGeoTransform().getGeoFromPixel(0, 0);
        double[] position = new double[3];
        convert = CRS.findMathTransform(DefaultGeographicCRS.WGS84, DefaultGeocentricCRS.CARTESIAN);
        convert.transform(latlon, 0, position, 0, 1);
        double earthradial = Math.pow(position[0] * position[0] + position[1] * position[1] + position[2] * position[2], 0.5);
        setSatelliteAltitude(radialdist - earthradial);

        // get incidence angles from gcps
        // !!possible to improve
        float firstIncidenceangle = (float) (this.gcps.get(0).getAngle());
        float lastIncidenceAngle = (float) (this.gcps.get(this.gcps.size() - 1).getAngle());
        setIncidenceNear(firstIncidenceangle < lastIncidenceAngle ? firstIncidenceangle : lastIncidenceAngle);
        setIncidenceFar(firstIncidenceangle > lastIncidenceAngle ? firstIncidenceangle : lastIncidenceAngle);

    } catch (TransformException | FactoryException | GeoTransformException ex) {
    	logger.error(ex.getMessage(),ex);
    }
    return true;
}
 
Example 20
Project: ms-gs-plugins   File: BoundsUpdateTransactionListener.java   View source code 5 votes vote down vote up
void updateLayerGroup(LayerGroupInfo lgi, ReferencedEnvelope dirtyRegion) {
    log.fine(()->"Updating bounds of "+lgi.prefixedName()+" in response to data change");
    ReferencedEnvelope bounds = lgi.getBounds();
    try {
        bounds.expandToInclude(new ReferencedEnvelope(dirtyRegion).transform(bounds.getCoordinateReferenceSystem(), true, 1000));
    } catch (MismatchedDimensionException | TransformException | FactoryException ex) {
        log.log(Level.WARNING, "Error while transforming changes to coordinate system of layer group "+lgi.prefixedName(), ex);
    }
    lgi.setBounds(bounds);
    catalog.save(lgi);
}
 
Example 21
Project: openrouteservice   File: JTS.java   View source code 5 votes vote down vote up
/**
 * Computes the orthodromic distance between two points. This method:
 * <p>
 * <ol>
 * <li>Transforms both points to geographic coordinates
 * (<var>latitude</var>,<var>longitude</var>).</li>
 * <li>Computes the orthodromic distance between the two points using ellipsoidal calculations.</li>
 * </ol>
 * <p>
 * The real work is performed by {@link GeodeticCalculator}. This convenience method simply
 * manages a pool of pre-defined geodetic calculators for the given coordinate reference system
 * in order to avoid repetitive object creation. If a large amount of orthodromic distances need
 * to be computed, direct use of {@link GeodeticCalculator} provides better performance than
 * this convenience method.
 * 
 * @param p1
 *            First point
 * @param p2
 *            Second point
 * @param crs
 *            Reference system the two points are in.
 * @return Orthodromic distance between the two points, in meters.
 * @throws TransformException
 *             if the coordinates can't be transformed from the specified CRS to a
 *             {@linkplain org.opengis.referencing.crs.GeographicCRS geographic CRS}.
 */
public static synchronized double orthodromicDistance(final Coordinate p1, final Coordinate p2,
        final CoordinateReferenceSystem crs) throws TransformException {
    ensureNonNull("p1", p1);
    ensureNonNull("p2", p2);
    ensureNonNull("crs", crs);

    /*
     * Need to synchronize because we use a single instance of a Map (CALCULATORS) as well as
     * shared instances of GeodeticCalculator and GeneralDirectPosition (POSITIONS). None of
     * them are thread-safe.
     */
    GeodeticCalculator gc = (GeodeticCalculator) CALCULATORS.get(crs);

    if (gc == null) {
        gc = new GeodeticCalculator(crs);
        CALCULATORS.put(crs, gc);
    }
    assert crs.equals(gc.getCoordinateReferenceSystem()) : crs;

    final GeneralDirectPosition pos = POSITIONS[Math.min(POSITIONS.length - 1, crs
            .getCoordinateSystem().getDimension())];
    pos.setCoordinateReferenceSystem(crs);
    copy(p1, pos.ordinates);
    gc.setStartingPosition(pos);
    copy(p2, pos.ordinates);
    gc.setDestinationPosition(pos);

    return gc.getOrthodromicDistance();
}
 
Example 22
Project: TomboloDigitalConnector   File: CoordinateUtils.java   View source code 5 votes vote down vote up
public static Coordinate eastNorthToLatLong(double x, double y, String sourceCrs, String targetCrs) throws FactoryException, MismatchedDimensionException, TransformException {
    CoordinateReferenceSystem targetCrsDecoded = CRS.decode(targetCrs);
    CoordinateReferenceSystem sourceCrsDecoded = CRS.decode(sourceCrs);

    CoordinateOperation op = new DefaultCoordinateOperationFactory().createOperation(sourceCrsDecoded, targetCrsDecoded);

    DirectPosition source = new GeneralDirectPosition(x, y);
    DirectPosition target = op.getMathTransform().transform(source, null);
    Double targetX = target.getOrdinate(0);
    Double targetY = target.getOrdinate(1);

    return new Coordinate(targetY, targetX);
}
 
Example 23
Project: TomboloDigitalConnector   File: AbstractGeotoolsDataStoreImporter.java   View source code 5 votes vote down vote up
private void withSubjects(FeatureReader<SimpleFeatureType, SimpleFeature> featureReader, DataStore dataStore, BiConsumer<SimpleFeature, Subject> fn) throws IOException, FactoryException, TransformException {
    MathTransform crsTransform = GeotoolsDataStoreUtils.makeCrsTransform(getSourceEncoding());

    while(featureReader.hasNext()) {
        SimpleFeature feature = featureReader.next();
        buildSubjectFromFeature(feature, crsTransform).ifPresent(subject -> {
            fn.accept(feature, subject);
            subjectBuffer.add(subject);
        });
        flushBufferIfRequired();
    }

    flushBuffer();
}
 
Example 24
Project: TomboloDigitalConnector   File: AbstractGeotoolsDataStoreImporter.java   View source code 5 votes vote down vote up
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 25
Project: TomboloDigitalConnector   File: AbstractGeotoolsDataStoreImporter.java   View source code 5 votes vote down vote up
private Optional<Subject> buildSubjectFromFeature(SimpleFeature feature, MathTransform crsTransform) throws TransformException {
    Optional<Geometry> optionalGeometry = extractNormalizedGeometry(feature, crsTransform);
    return optionalGeometry.flatMap(geometry -> {
        Subject subject = applyFeatureAttributesToSubject(new Subject(), feature);
        subject.setShape(geometry);
        return Optional.of(subject);
    });
}
 
Example 26
Project: igsn30   File: SpatialUtilities.java   View source code 5 votes vote down vote up
public static Geometry convertUTM_MGA942Geographic_EPSG4326(Double easting, Double northing, String zone) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException, TransformException{
	CoordinateReferenceSystem geographic = CRS.decode("EPSG:4326", false);
	CoordinateReferenceSystem geographic2 = ReferencingFactoryFinder.getCRSAuthorityFactory(
			"EPSG", null).createCoordinateReferenceSystem("4326");
	

	
	CoordinateReferenceSystem utm = ReferencingFactoryFinder.getCRSAuthorityFactory(
			"EPSG", null).createCoordinateReferenceSystem("283"+zone);
	
	CoordinateOperationFactory coFactory = ReferencingFactoryFinder
			.getCoordinateOperationFactory(null);
	
	CoordinateReferenceSystem sourceCRS = utm;		
	CoordinateReferenceSystem targetCRS = geographic;

	GeometryFactory gf = new GeometryFactory();
       Coordinate coord = new Coordinate( easting, northing );
       Point point = gf.createPoint( coord );
       
	
	MathTransform mathTransform =CRS.findMathTransform( sourceCRS, targetCRS,true );
	Geometry g2 = JTS.transform(point, mathTransform);
	
	//VT: Flip around to correct the lat lon from the utm to geographic transformation
	Coordinate[] original = g2.getCoordinates();
	for(int i = 0; i < original.length; i++){
	    Double swapValue = original[i].x;
	    original[i].x = original[i].y;
	    original[i].y = swapValue;
	}
    
	return g2;
}
 
Example 27
Project: igsn30   File: TEST.java   View source code 5 votes vote down vote up
public static void main(String [] args) throws NoSuchAuthorityCodeException, FactoryRegistryException, FactoryException, MismatchedDimensionException, TransformException{

		
		String zone = "52";
		double easting =596450.153;
		double northing = 6680793.777;
		System.out.print(SpatialUtilities.convertUTM_MGA942Geographic_EPSG4326(easting, northing, zone));
		
//		String zone = "53";
//		double easting =616450.153;
//		double northing = 6680793.777;
//		System.out.print(SpatialUtilities.convertUTM_MGA942Geographic_EPSG4326(easting, northing, zone));
		
	}
 
Example 28
Project: georocket   File: CoordinateTransformer.java   View source code 5 votes vote down vote up
/**
 * Transform an array of coordinates to {@link DefaultGeographicCRS#WGS84}
 * @param from the source array of coordinates
 * @param dimension the dimension of the source coordinates. Allowed values
 * are &lt;= 0, 2 and 3. If the value is &lt;= 0 the dimension will be
 * guessed (see {@link #guessDimension(double[])}).
 * @return a new array with the destination coordinates of null if the dimension
 * in unknown or the source coordinates could not be transformed
 * @throws TransformException if the coordinates could not be transformed
 */
public double[] transform(double[] from, int dimension) throws TransformException {
  if (dimension <= 0) {
    dimension = guessDimension(from);
  }

  if (dimension != 2 && dimension != 3) {
    return null;
  }

  if (from.length % dimension != 0) {
    return null;
  }

  int count = from.length / dimension;

  for (int i = 0; i < from.length; i += dimension) {
    if (flipped) {
      double tmp = from[i];
      from[i] = from[i + 1];
      from[i + 1] = tmp;
    }
  }

  double[] destination = new double[count * 2];
  transform.transform(from, 0, destination, 0, count);

  return destination;
}
 
Example 29
Project: downloadclient   File: WMSMapSwing.java   View source code 5 votes vote down vote up
private void convertAndDisplayBoundingBox(
        Double x1,
        Double x2,
        Double y1,
        Double y2,
        CoordinateReferenceSystem sourceCRS,
        CoordinateReferenceSystem targetCRS
) throws TransformException, FactoryException {
    com.vividsolutions.jts.geom.Point p1 = convertDoublesToPoint(
            x1,
            y1,
            sourceCRS,
            targetCRS);
    com.vividsolutions.jts.geom.Point p2 = convertDoublesToPoint(
            x2,
            y2,
            sourceCRS,
            targetCRS);
    ReferencedEnvelope re = new ReferencedEnvelope(targetCRS);
    re.include(p1.getX(), p1.getY());
    re.include(p2.getX(), p2.getY());
    DirectPosition lowerCorner = re.getLowerCorner();
    DirectPosition upperCorner = re.getUpperCorner();
    if (lowerCorner != null && upperCorner != null) {
        double valX1 = lowerCorner.getCoordinate()[0];
        double valY1 = lowerCorner.getCoordinate()[1];
        double valX2 = upperCorner.getCoordinate()[0];
        double valY2 = upperCorner.getCoordinate()[1];
        if (CRS.getProjectedCRS(targetCRS) == null) {
            this.coordinateX1TextField.setText(String.valueOf(
                    Math.round(valX1 * HOUNDREDTHOUSAND) / HOUNDREDTHOUSAND
            ));
            this.coordinateY1TextField.setText(String.valueOf(
                    Math.round(valY1 * HOUNDREDTHOUSAND) / HOUNDREDTHOUSAND
            ));
            this.coordinateX2TextField.setText(String.valueOf(
                    Math.round(valX2 * HOUNDREDTHOUSAND) / HOUNDREDTHOUSAND
            ));
            this.coordinateY2TextField.setText(String.valueOf(
                    Math.round(valY2 * HOUNDREDTHOUSAND) / HOUNDREDTHOUSAND
            ));
        } else {
            this.coordinateX1TextField.setText(String.valueOf(
                    Math.round((float) valX1)
            ));
            this.coordinateY1TextField.setText(String.valueOf(
                    Math.round((float) valY1)
            ));
            this.coordinateX2TextField.setText(String.valueOf(
                    Math.round((float) valX2)
            ));
            this.coordinateY2TextField.setText(String.valueOf(
                    Math.round((float) valY2)
            ));
        }
    }
}
 
Example 30
Project: downloadclient   File: WMSMapSwing.java   View source code 5 votes vote down vote up
private com.vividsolutions.jts.geom.Point convertDoublesToPoint(
        Double x,
        Double y,
        CoordinateReferenceSystem sourceCRS,
        CoordinateReferenceSystem targetCRS)
throws TransformException, FactoryException {
    com.vividsolutions.jts.geom.GeometryFactory gf = new
            com.vividsolutions.jts.geom.GeometryFactory();
    com.vividsolutions.jts.geom.Coordinate coo = new com
            .vividsolutions.jts.geom.Coordinate(x, y);
    com.vividsolutions.jts.geom.Point p = gf.createPoint(coo);
    MathTransform transform = CRS.findMathTransform(
            sourceCRS, targetCRS);
    return (com.vividsolutions.jts.geom.Point) JTS.transform(p, transform);
}
 
Example 31
Project: vgi-analytics-framework   File: VgiAnalysisUpdateGeometry.java   View source code 5 votes vote down vote up
@Override
	public void analyze(IVgiOperation operation, Date timePeriod) {

		if (!operation.getVgiOperationType().equals(VgiOperationType.OP_ADD_NODE) && !operation.getVgiOperationType().equals(VgiOperationType.OP_MODIFY_WAY_COORDINATE)) return;
		
		if (!data.containsKey(operation.getVersion())) {
			data.put(operation.getVersion(), new GeometryUpdates());
		}
		GeometryUpdates geomUpdates = data.get(operation.getVersion());
		
		Point currentCoordinate = null;
		
		try {
//			transform = CRS.findMathTransform(sourceCRS, targetCRS, true);
			
			Point point = geometryFactory.createPoint(operation.getCoordinate());
			point.setSRID(4326);

//			MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
			currentCoordinate = (Point)JTS.transform( point, transform);
//		} catch (FactoryException e) {
//			e.printStackTrace();
		} catch (TransformException e) {
			e.printStackTrace();
		}
		
		if (geomUpdates.coordinates.containsKey(operation.getRefId())) {
			geomUpdates.updatesCount++;
			geomUpdates.sumCoordinateDelta += geomUpdates.coordinates.get(operation.getRefId()).distance(currentCoordinate);
			
		}
		
		geomUpdates.coordinates.put(operation.getRefId(), currentCoordinate);
		
	}
 
Example 32
Project: osmosis-nls-dem   File: NLSDEMTask.java   View source code 5 votes vote down vote up
@Override
public void process(NodeContainer nodec) {
    Node node = nodec.getEntity();
    double lat = node.getLatitude();
    double lon = node.getLongitude();

    // Transform to EPSG:3067
    DirectPosition2D ptDst = new DirectPosition2D(targetCRS);
    try {
        transform.transform(new DirectPosition2D(sourceCRS, lon, lat), ptDst);

        String tm35MapSheet = TM35Utils.reverseGeocode(ptDst.x, ptDst.y, TM35Scale.SCALE_10000);

        GridCoverage2D gc = ready.get(tm35MapSheet);

        if (gc != null) {
            // Do the computation
            processReady(gc, ptDst, node);
        } else {
            // Download tiff async

            processing.compute(tm35MapSheet, (sheetKey, currentSet) -> {
                if (currentSet == null)
                    currentSet = new HashSet<>();

                currentSet.add(new TranslatedNode(node, ptDst));
                return currentSet;
            });
            submitTiffQuerying(tm35MapSheet);
        }
        processReadyItems();

    } catch (MismatchedDimensionException | TransformException e) {
        LOGGER.log(Level.WARNING,
                "Could not transform lat=" + lat + ", lon=" + lon + " from " + sourceCRS + " to " + targetCRS, e);
    }
}
 
Example 33
Project: online-whatif   File: ProjectController.java   View source code 5 votes vote down vote up
/**
 * Gets the all projects.
 *
 * @param roleId
 *          the role id
 * @return the all projects
 * @throws WifInvalidConfigException
 *           the wif invalid config exception
 * @throws WifInvalidInputException
 *           the wif invalid input exception
 * @throws NoSuchAuthorityCodeException
 *           the no such authority code exception
 * @throws FactoryException
 *           the factory exception
 * @throws TransformException
 *           the transform exception
 * @throws ParseException
 *           the parse exception
 * @throws CQLException
 *           the cQL exception
 */
@RequestMapping(method = RequestMethod.GET, value = "/")
@ResponseStatus(HttpStatus.OK)
@SuppressWarnings({ "unchecked", "rawtypes" })
public @ResponseBody
List<WifProject> getAllProjects(
    @RequestHeader(HEADER_USER_ID_KEY) final String roleId,
    final HttpServletResponse response) throws WifInvalidConfigException,
WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException,
TransformException, ParseException, CQLException {

  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY);
  response
  .setHeader("Access-Control-Allow-Headers",
      "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

  LOGGER.info("*******>> getAllProjectsNoMapping");

  try {
    return projectService.getAllProjects(roleId);
  } catch (final Exception e) {
    LOGGER.error("find a project failed {}");
    throw new WifInvalidInputException("find a project failed {}");
  }
}
 
Example 34
Project: online-whatif   File: ProjectController.java   View source code 5 votes vote down vote up
/**
 * Gets the all project names.
 *
 * @param roleId
 *          the role id
 * @return
 * @return the all projects names
 * @throws WifInvalidConfigException
 *           the wif invalid config exception
 * @throws WifInvalidInputException
 *           the wif invalid input exception
 * @throws NoSuchAuthorityCodeException
 *           the no such authority code exception
 * @throws FactoryException
 *           the factory exception
 * @throws TransformException
 *           the transform exception
 * @throws ParseException
 *           the parse exception
 * @throws CQLException
 *           the cQL exception
 */
@RequestMapping(method = RequestMethod.GET, value = "/projectNames")
@ResponseStatus(HttpStatus.OK)
@SuppressWarnings({ "unchecked", "rawtypes" })
public @ResponseBody
List<String> getAllProjectNames(
    @RequestHeader(HEADER_USER_ID_KEY) final String roleId,
    final HttpServletResponse response) throws WifInvalidConfigException,
WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException,
TransformException, ParseException, CQLException {

  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY);
  response
  .setHeader("Access-Control-Allow-Headers",
      "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

  LOGGER.info("*******>> getAllProject names");
  final List<String> lst = new ArrayList<String>();
  try {
    final List<WifProject> prjList = projectService.getAllProjects(roleId);
    for (final WifProject wif : prjList) {
      lst.add(wif.getLabel());
    }
    return lst;
  } catch (final Exception e) {
    LOGGER.error("getAllProject names {}");
    throw new WifInvalidInputException("find a project failed {}");
  }
}
 
Example 35
Project: online-whatif   File: ProjectController.java   View source code 5 votes vote down vote up
/**
 * Gets the report projects.
 *
 * @param roleId
 *          the role id
 * @return the all projects
 * @throws WifInvalidConfigException
 *           the wif invalid config exception
 * @throws WifInvalidInputException
 *           the wif invalid input exception
 * @throws NoSuchAuthorityCodeException
 *           the no such authority code exception
 * @throws FactoryException
 *           the factory exception
 * @throws TransformException
 *           the transform exception
 * @throws ParseException
 *           the parse exception
 * @throws CQLException
 *           the cQL exception
 */
@RequestMapping(method = RequestMethod.GET, value = "/getReportProjects")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
List<String> getReportProjects(
    @RequestHeader(HEADER_USER_ID_KEY) final String roleId,
    final HttpServletResponse response) throws WifInvalidConfigException,
WifInvalidInputException, NoSuchAuthorityCodeException, FactoryException,
TransformException, ParseException, CQLException {

  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
  response.setHeader("Access-Control-Allow-Headers", HEADER_USER_ID_KEY);
  response
  .setHeader("Access-Control-Allow-Headers",
      "Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

  LOGGER.info("*******>> getReportProjects");
  final List<String> lst = new ArrayList<String>();
  try {
    final List<WifProject> prjs= projectService.getAllProjects(roleId);
    for (final WifProject prj : prjs) {
      final SimpleDateFormat mdyFormat = new SimpleDateFormat("dd/MM/yyyy");
      lst.add(prj.getRoleOwner() + "|" + prj.getName() + "|" + mdyFormat.format(prj.getCreationDate()));
    }
    return lst;
  } catch (final Exception e) {
    LOGGER.error("getReportProjects failed {}");
    throw new WifInvalidInputException("getReportProjects failed {}");
  }
}
 
Example 36
Project: online-whatif   File: SuitabilityScenarioServiceImpl.java   View source code 5 votes vote down vote up
@Override
public Boolean getWMSOutcome(final String id, final String areaAnalyzed, final String crsArea)
    throws WifInvalidInputException, WifInvalidConfigException,
    MismatchedDimensionException, NoSuchAuthorityCodeException,
    FactoryException, TransformException, ParseException, IOException,
    CQLException, SuitabilityAnalysisFailedException, ParsingException {
  final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
  return suitabilityAnalyzer.doSuitabilityAnalysisWMS(suitabilityScenario,
      areaAnalyzed, crsArea);
}
 
Example 37
Project: online-whatif   File: SuitabilityScenarioServiceImpl.java   View source code 5 votes vote down vote up
@Override
public SimpleFeatureCollection getOutcome(final String id, final String areaAnalyzed,
    final String crsArea) throws WifInvalidInputException,
WifInvalidConfigException, MismatchedDimensionException,
NoSuchAuthorityCodeException, CQLException, FactoryException,
TransformException, ParseException, ParsingException,
DatabaseFailedException {
  final SuitabilityScenario suitabilityScenario = getSuitabilityScenario(id);
  return suitabilityAnalyzer.doSuitabilityAnalysis(suitabilityScenario,
      areaAnalyzed, crsArea);
}
 
Example 38
Project: gtfs-lib   File: GeoUtils.java   View source code 5 votes vote down vote up
@Deprecated
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 39
Project: gtfs-lib   File: GeoUtils.java   View source code 5 votes vote down vote up
/** Get the length of a linestring in meters */
public static double getDistance(LineString tripGeometry) {
  double distance = 0;
  for (int i = 0; i < tripGeometry.getNumPoints() - 1; i++) {
    try {
      distance += JTS.orthodromicDistance(tripGeometry.getCoordinateN(i), tripGeometry.getCoordinateN(i + 1), DefaultGeographicCRS.WGS84);
    } catch (TransformException e) {
      throw new RuntimeException(e);
    }
  }

  return distance;
}
 
Example 40
Project: s3tbx-c2rcc   File: MsiProductSignatureTest.java   View source code 5 votes vote down vote up
@Test
public void testProductSignature_Default_AsRrs() throws FactoryException, TransformException {

    C2rccMsiOperator operator = createDefaultOperator();
    operator.setOutputAsRrs(true);
    operator.setOutputOos(true);
    Product targetProduct = operator.getTargetProduct();

    assertDefaults(targetProduct, true);
    assertBands(targetProduct, EXPECTED_OOS_RTOSA);
    assertBands(targetProduct, EXPECTED_OOS_RRS);

}