Java Code Examples for org.opengis.referencing.crs.CoordinateReferenceSystem

The following examples show how to use org.opengis.referencing.crs.CoordinateReferenceSystem. These examples are extracted from open source projects. 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 Project: hortonmachine   Source File: CrsUtilities.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Fill the prj file with the actual map projection.
 *
 * @param filePath  the path to the regarding data or prj file.
 * @param extention the extention of the data file. If <code>null</code>, the crs is written to filePath directly.
 * @param crs       the {@link CoordinateReferenceSystem} to write.
 *
 * @throws IOException
 */
@SuppressWarnings("nls")
public static void writeProjectionFile( String filePath, String extention, CoordinateReferenceSystem crs )
        throws IOException {
    /*
     * fill a prj file
     */
    String prjPath = null;
    if (extention != null && filePath.toLowerCase().endsWith("." + extention)) {
        int dotLoc = filePath.lastIndexOf(".");
        prjPath = filePath.substring(0, dotLoc);
        prjPath = prjPath + ".prj";
    } else {
        if (!filePath.endsWith(".prj")) {
            prjPath = filePath + ".prj";
        } else {
            prjPath = filePath;
        }
    }

    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(prjPath))) {
        bufferedWriter.write(crs.toWKT());
    }
}
 
Example 2
@Override
public CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameters,
                                        GeodeticDatum datum) throws FactoryException {
    final CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
    // in some cases, depending on the parameters set, the effective transformation can be different
    // from the transformation given by the OperationMethod.
    // So we create a new one
    final MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);
    final MathTransform transform = mtFactory.createParameterizedTransform(parameters);
    final DefaultOperationMethod operationMethod = new DefaultOperationMethod(transform);

    final Conversion conversion = new DefiningConversion(AbstractIdentifiedObject.getProperties(operationMethod),
                                                         operationMethod, transform);

    final HashMap<String, Object> baseCrsProperties = new HashMap<String, Object>();
    baseCrsProperties.put("name", datum.getName().getCode());
    GeographicCRS baseCrs = crsFactory.createGeographicCRS(baseCrsProperties,
                                                           datum,
                                                           DefaultEllipsoidalCS.GEODETIC_2D);

    final HashMap<String, Object> projProperties = new HashMap<String, Object>();
    projProperties.put("name", conversion.getName().getCode() + " / " + datum.getName().getCode());
    return crsFactory.createProjectedCRS(projProperties, baseCrs, conversion, DefaultCartesianCS.PROJECTED);
}
 
Example 3
Source Project: sis   Source File: EnvelopeOperationTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a feature type with a bounds operation.
 * The feature contains the following properties:
 *
 * <ul>
 *   <li>{@code name} as a {@link String}</li>
 *   <li>{@code classes} as a {@link Polygon}</li>
 *   <li>{@code climbing wall} as a {@link Point}</li>
 *   <li>{@code gymnasium} as a {@link Polygon}</li>
 *   <li>{@code sis:geometry} as a link to the default geometry</li>
 *   <li>{@code bounds} as the feature envelope attribute.</li>
 * </ul>
 *
 * @param  defaultGeometry  1 for using "classes" as the default geometry, or 3 for "gymnasium".
 * @return the feature for a school.
 */
private static DefaultFeatureType school(final int defaultGeometry) throws FactoryException {
    final DefaultAttributeType<?> standardCRS = new DefaultAttributeType<>(
            name(AttributeConvention.CRS_CHARACTERISTIC), CoordinateReferenceSystem.class, 1, 1, HardCodedCRS.WGS84_φλ);

    final DefaultAttributeType<?> normalizedCRS = new DefaultAttributeType<>(
            name(AttributeConvention.CRS_CHARACTERISTIC), CoordinateReferenceSystem.class, 1, 1, HardCodedCRS.WGS84);

    final AbstractIdentifiedType[] attributes = {
        new DefaultAttributeType<>(name("name"),          String.class,  1, 1, null),
        new DefaultAttributeType<>(name("classes"),       Polygon.class, 1, 1, null, standardCRS),
        new DefaultAttributeType<>(name("climbing wall"), Point.class,   1, 1, null, standardCRS),
        new DefaultAttributeType<>(name("gymnasium"),     Polygon.class, 1, 1, null, normalizedCRS),
        null,
        null
    };
    attributes[4] = FeatureOperations.link(name(AttributeConvention.GEOMETRY_PROPERTY), attributes[defaultGeometry]);
    attributes[5] = FeatureOperations.envelope(name("bounds"), null, attributes);
    return new DefaultFeatureType(name("school"), false, null, attributes);
}
 
Example 4
Source Project: hortonmachine   Source File: TestMapcalc.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void testMapcalc3() throws Exception {
    double[][] elevationData = HMTestMaps.pitData;
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();
    GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("ele", elevationData, envelopeParams, crs, true);

    List<GridCoverage2D> maps = Arrays.asList(elevationCoverage);

    OmsMapcalc mapcalc = new OmsMapcalc();
    mapcalc.inRasters = maps;
    mapcalc.pFunction = "images{ele=read; dest=write;} dest = xres()*yres();";
    mapcalc.process();

    GridCoverage2D outMap = mapcalc.outRaster;

    RenderedImage renderedImage = outMap.getRenderedImage();
    // printImage(renderedImage);

    checkEqualsSinlgeValue(renderedImage, 900.0, 0.000000001);
}
 
Example 5
Source Project: gama   Source File: SwtMapPane.java    License: 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 6
Source Project: sis   Source File: CommonAuthorityFactory.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the "Computer display" reference system (CRS:1). This is rarely used.
 */
private synchronized CoordinateReferenceSystem displayCRS() throws FactoryException {
    if (displayCRS == null) {
        final CSFactory csFactory = DefaultFactories.forBuildin(CSFactory.class);
        final CartesianCS cs = csFactory.createCartesianCS(
                Collections.singletonMap(CartesianCS.NAME_KEY, "Computer display"),
                csFactory.createCoordinateSystemAxis(Collections.singletonMap(CartesianCS.NAME_KEY, "i"), "i", AxisDirection.EAST,  Units.PIXEL),
                csFactory.createCoordinateSystemAxis(Collections.singletonMap(CartesianCS.NAME_KEY, "j"), "j", AxisDirection.SOUTH, Units.PIXEL));

        final Map<String,Object> properties = new HashMap<>(4);
        properties.put(EngineeringDatum.NAME_KEY, cs.getName());
        properties.put(EngineeringDatum.ANCHOR_POINT_KEY, "Origin is in upper left.");
        displayCRS = DefaultFactories.forBuildin(CRSFactory.class).createEngineeringCRS(properties,
                     DefaultFactories.forBuildin(DatumFactory.class).createEngineeringDatum(properties), cs);
    }
    return displayCRS;
}
 
Example 7
Source Project: sis   Source File: CRS.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the first temporal coordinate reference system found in the given CRS, or {@code null} if there is none.
 * If the given CRS is already an instance of {@code TemporalCRS}, then this method returns it as-is.
 * Otherwise if the given CRS is compound, then this method searches for the first temporal component
 * in the order of the {@linkplain #getSingleComponents(CoordinateReferenceSystem) single components list}.
 *
 * @param  crs  the coordinate reference system, or {@code null}.
 * @return the first temporal CRS, or {@code null} if none.
 *
 * @category information
 */
public static TemporalCRS getTemporalComponent(final CoordinateReferenceSystem crs) {
    if (crs instanceof TemporalCRS) {
        return (TemporalCRS) crs;
    }
    if (crs instanceof CompoundCRS) {
        final CompoundCRS cp = (CompoundCRS) crs;
        for (final CoordinateReferenceSystem c : cp.getComponents()) {
            final TemporalCRS candidate = getTemporalComponent(c);
            if (candidate != null) {
                return candidate;
            }
        }
    }
    return null;
}
 
Example 8
Source Project: hortonmachine   Source File: TestTca.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void testNewTca() throws Exception {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] flowData = HMTestMaps.flowData;
    GridCoverage2D flowCoverage = CoverageUtilities.buildCoverage("flow", flowData, envelopeParams, crs, true);

    OmsTca tca = new OmsTca();
    tca.inFlow = flowCoverage;
    tca.pm = pm;
    tca.process();
    GridCoverage2D tcaCoverage = tca.outTca;

    // PrintUtilities.printCoverageData(tcaCoverage);
    checkMatrixEqual(tcaCoverage.getRenderedImage(), HMTestMaps.tcaData);
}
 
Example 9
@Override
public Geometry transform(Geometry geometry, CoordinateReferenceSystem sourceCrs,
		CoordinateReferenceSystem targetCrs) throws GeomajasException {
	if (sourceCrs == targetCrs) { // NOPMD
		// only works when the caching of the CRSs works
		return geometry;
	}
	Crs source, target;
	if (sourceCrs instanceof Crs) {
		source = (Crs) sourceCrs;
	} else {
		source = getCrs2(getCodeFromCrs(sourceCrs));
	}
	if (targetCrs instanceof Crs) {
		target = (Crs) targetCrs;
	} else {
		target = getCrs2(getCodeFromCrs(targetCrs));
	}

	CrsTransform crsTransform = getCrsTransform(source, target);
	return transform(geometry, crsTransform);
}
 
Example 10
/**
* Test module with mode=0.
*/
public void testExtractNetwork0() throws Exception {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] flowData = HMTestMaps.flowData;
    GridCoverage2D flowCoverage = CoverageUtilities.buildCoverage("flow", flowData, envelopeParams, crs, true);
    double[][] tcaData = HMTestMaps.tcaData;
    GridCoverage2D tcaCoverage = CoverageUtilities.buildCoverage("tca", tcaData, envelopeParams, crs, true);

    OmsExtractNetwork extractNetwork = new OmsExtractNetwork();
    extractNetwork.pm = pm;
    extractNetwork.inFlow = flowCoverage;
    extractNetwork.inTca = tcaCoverage;
    extractNetwork.pMode = Variables.TCA;
    extractNetwork.pThres = 5;
    extractNetwork.process();

    GridCoverage2D networkCoverage = extractNetwork.outNet;
    checkMatrixEqual(networkCoverage.getRenderedImage(), HMTestMaps.extractNet0Data, 0.01);
}
 
Example 11
Source Project: sis   Source File: CoordinateOperationsTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests {@link CoordinateOperations#wrapAroundChanges(CoordinateReferenceSystem, CoordinateSystem)}.
 */
@Test
@DependsOnMethod("testIsWrapAround")
public void testWrapAroundChanges() {
    CoordinateReferenceSystem sourceCRS = HardCodedCRS.WGS84_3D;
    CoordinateSystem          targetCS = HardCodedCS.GEODETIC_2D;
    assertTrue("(λ,φ,h) → (λ,φ)", CoordinateOperations.wrapAroundChanges(sourceCRS, targetCS).isEmpty());

    sourceCRS = HardCodedCRS.WGS84_3D.forConvention(AxesConvention.POSITIVE_RANGE);
    assertArrayEquals("(λ′,φ,h) → (λ,φ)", new Integer[] {0},
            CoordinateOperations.wrapAroundChanges(sourceCRS, targetCS).toArray());

    targetCS = HardCodedCS.GEODETIC_φλ;
    assertArrayEquals("(λ′,φ,h) → (φ,λ)", new Integer[] {1},
            CoordinateOperations.wrapAroundChanges(sourceCRS, targetCS).toArray());

    sourceCRS = HardCodedConversions.mercator((GeographicCRS) sourceCRS);
    assertArrayEquals("(λ′,φ,h) → (φ,λ)", new Integer[] {1},
            CoordinateOperations.wrapAroundChanges(sourceCRS, targetCS).toArray());

}
 
Example 12
private void createPolygons( CoordinateReferenceSystem crs, GeometryFactory gf, List<Geometry> polygons ) {
    outMap = new DefaultFeatureCollection();
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName(POLYGON);
    b.setCRS(crs);
    b.add("the_geom", Polygon.class);
    b.add("id", Long.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder fbuilder = new SimpleFeatureBuilder(type);

    long index = 0;
    int numGeometries = polygons.size();
    for( int i = 0; i < numGeometries; i++ ) {
        Geometry geometry = polygons.get(i);
        Object[] values = new Object[]{geometry, index++};
        fbuilder.addAll(values);
        SimpleFeature feature = fbuilder.buildFeature(null);
        ((DefaultFeatureCollection) outMap).add(feature);
    }
}
 
Example 13
/**
 * Generates the bounding box from the ui.
 *
 * @return the b box
 */
private ReferencedEnvelope getBBox() {
    if (xMinTextField == null) {
        return null;
    }

    double minX =
            xMinTextField.getText().isEmpty() ? 0.0 : Double.valueOf(xMinTextField.getText());
    double maxX =
            xMaxTextField.getText().isEmpty() ? 0.0 : Double.valueOf(xMaxTextField.getText());
    double minY =
            yMinTextField.getText().isEmpty() ? 0.0 : Double.valueOf(yMinTextField.getText());
    double maxY =
            yMaxTextField.getText().isEmpty() ? 0.0 : Double.valueOf(yMaxTextField.getText());

    ValueComboBoxData crsDataValue = crsComboBox.getSelectedValue();

    CoordinateReferenceSystem crs = null;
    try {
        if (crsDataValue != null) {
            crs = CRS.decode(crsDataValue.getKey());
        }
    } catch (FactoryException e) {
        ConsoleManager.getInstance().exception(this, e);
    }

    return new ReferencedEnvelope(minX, maxX, minY, maxY, crs);
}
 
Example 14
public static GridGeometry2D gridGeometryFromRegionParams( HashMap<String, Double> envelopeParams,
        CoordinateReferenceSystem crs ) {
    double west = envelopeParams.get(WEST);
    double south = envelopeParams.get(SOUTH);
    double east = envelopeParams.get(EAST);
    double north = envelopeParams.get(NORTH);
    int rows = envelopeParams.get(ROWS).intValue();
    int cols = envelopeParams.get(COLS).intValue();

    return gridGeometryFromRegionValues(north, south, east, west, cols, rows, crs);
}
 
Example 15
/**
 * Finish service initialization.
 *
 * @throws GeomajasException oops
 */
@PostConstruct
protected void postConstruct() throws GeomajasException {
	if (null != crsDefinitions) {
		for (CrsInfo crsInfo : crsDefinitions.values()) {
			try {
				CoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());
				String code = crsInfo.getKey();
				crsCache.put(code, CrsFactory.getCrs(code, crs));
			} catch (FactoryException e) {
				throw new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());
			}
		}
	}
	if (null != crsTransformDefinitions) {
		for (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {
			String key = getTransformKey(crsTransformInfo);
			transformCache.put(key, getCrsTransform(key, crsTransformInfo));
		}
	}
	GeometryFactory factory = new GeometryFactory();
	EMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));
	EMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));
	EMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));
	EMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));
	EMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!
	EMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!
	EMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));
}
 
Example 16
Source Project: sldeditor   Source File: CoordManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the WGS84 coordinate reference object.
 *
 * @return the WGS84 coordinate reference system
 */
public CoordinateReferenceSystem getWGS84() {
    if (defaultCRS == null) {
        defaultCRS = getCRS(WGS84);
    }
    return defaultCRS;
}
 
Example 17
Source Project: sis   Source File: ComparisonWithEPSG.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Compares a projected CRS parsed from a WKT with a the CRS built from EPSG database.
 * The later is taken as the reference.
 */
private static void compare(final String wkt, final int epsg) throws FactoryException {
    final CoordinateReferenceSystem crs = CRS.fromWKT(wkt);
    final EPSGFactory factory = TestFactorySource.factory;
    assumeNotNull(factory);
    final CoordinateReferenceSystem reference = factory.createProjectedCRS(Integer.toString(epsg));
    assertEqualsIgnoreMetadata(reference, crs);
}
 
Example 18
private String convertToWkt(CoordinateReferenceSystem crs) {
    // according to GeoTools it is better to use to String or the Formattable directly
    // https://osgeo-org.atlassian.net/browse/GEOS-4746
    // But first try toWKT(), there must be a reason for being strict in this method.
    try {
        return crs.toWKT();
    } catch (UnformattableObjectException e) {
        SystemUtils.LOG.log(Level.WARNING, "Could not strictly convert CRS to WKT. " +
                "Used lenient method instead.", e);
        return crs.toString();
    }
}
 
Example 19
Source Project: geowave   Source File: OrthodromicDistancePartitioner.java    License: Apache License 2.0 5 votes vote down vote up
public OrthodromicDistancePartitioner(
    final CoordinateReferenceSystem crs,
    final CommonIndexModel indexModel,
    final DimensionExtractor<T> dimensionExtractor,
    final double[] distancePerDimension,
    final Unit<Length> geometricDistanceUnit) {
  super(distancePerDimension);
  this.crs = crs;
  this.crsName = crs.getIdentifiers().iterator().next().toString();
  this.geometricDistanceUnit = geometricDistanceUnit;
  this.dimensionExtractor = dimensionExtractor;
  initIndex(indexModel, distancePerDimension);
}
 
Example 20
Source Project: sis   Source File: LocationFormat.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a CRS equivalent to the given one but with (longitude, latitude) or (easting, northing) axis order.
 * This method does not change the units of measurement. If the given CRS is already normalized, then it is
 * returned unchanged.
 */
private static CoordinateReferenceSystem normalize(final CoordinateReferenceSystem crs) {
    if (crs != null) {
        AbstractCRS normalized = AbstractCRS.castOrCopy(crs);
        if (normalized != (normalized = normalized.forConvention(AxesConvention.DISPLAY_ORIENTED))) {
            return normalized;
        }
    }
    return crs;
}
 
Example 21
Source Project: hortonmachine   Source File: TestShalstab.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void testShalstab() throws Exception {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] slopeData = HMTestMaps.slopeData;
    GridCoverage2D slopeCoverage = CoverageUtilities.buildCoverage("slope", slopeData, envelopeParams, crs, true);
    double[][] abData = HMTestMaps.abData;
    GridCoverage2D abCoverage = CoverageUtilities.buildCoverage("ab", abData, envelopeParams, crs, true);
    
    OmsShalstab shalstab = new OmsShalstab();
    shalstab.inSlope = slopeCoverage;
    shalstab.inTca = abCoverage;
    shalstab.pTrasmissivity = 0.001;
    shalstab.pCohesion = 0.0;
    shalstab.pSdepth = 2.0;
    shalstab.pRho = 1.6;
    shalstab.pTgphi = 0.7;
    shalstab.pQ = 0.05;
    shalstab.pm = pm;

    shalstab.process();

    GridCoverage2D qcritCoverage = shalstab.outQcrit;
    GridCoverage2D classiCoverage = shalstab.outShalstab;

    checkMatrixEqual(qcritCoverage.getRenderedImage(), HMTestMaps.qcritmapData, 0);
    checkMatrixEqual(classiCoverage.getRenderedImage(), HMTestMaps.classimapData, 0);
}
 
Example 22
@Test
@DirtiesContext
public void testSaveOrUpdateUpdateArea() throws Exception {
	Filter filter;
	List<InternalFeature> oldFeatures;
	List<InternalFeature> newFeatures;
	InternalFeature feature;
	CoordinateReferenceSystem crs = beanLayer.getCrs();

	login("marino");
	// should be able to update feature "2"
	filter = filterService.createFidFilter(new String[]{"2"});
	oldFeatures = layerService.getFeatures(LAYER_ID, crs, filter, null,
			VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
	Assert.assertEquals(1, oldFeatures.size());
	feature = oldFeatures.get(0);
	newFeatures = new ArrayList<InternalFeature>();
	feature = feature.clone();
	newFeatures.add(feature);
	feature.getAttributes().put(STRING_ATTR, new StringAttribute("changed"));
	layerService.saveOrUpdate(LAYER_ID, crs, oldFeatures, newFeatures);
	// should not be able to update feature "3"
	filter = filterService.createFidFilter(new String[]{"3"});
	oldFeatures = layerService.getFeatures(LAYER_ID, crs, filter, null,
			VectorLayerService.FEATURE_INCLUDE_ATTRIBUTES);
	Assert.assertEquals(1, oldFeatures.size());
	feature = oldFeatures.get(0);
	newFeatures = new ArrayList<InternalFeature>();
	feature = feature.clone();
	newFeatures.add(feature);
	feature.getAttributes().put(STRING_ATTR, new StringAttribute("changed"));
	try {
		layerService.saveOrUpdate(LAYER_ID, crs, oldFeatures, newFeatures);
		Assert.fail("update area not checked when updating");
	} catch (GeomajasException ge) {
		Assert.assertEquals(ExceptionCode.FEATURE_UPDATE_PROHIBITED, ge.getExceptionCode());
	}
}
 
Example 23
@SuppressWarnings("nls")
public void testRasterVectorIntersector() throws Exception {
    RegionMap ep = HMTestMaps.getEnvelopeparams();
    SimpleFeatureCollection testLeftFC = HMTestMaps.getTestLeftFC();

    double[][] elevationData = HMTestMaps.mapData;
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();
    GridCoverage2D elevationCoverage = CoverageUtilities.buildCoverage("elevation", elevationData, ep, crs, true);

    double[][] test = new double[elevationData.length][elevationData[0].length];
    double[][] testInverse = new double[elevationData.length][elevationData[0].length];
    for( int i = 0; i < elevationData.length; i++ ) {
        for( int j = 0; j < elevationData[0].length; j++ ) {
            if (j < 5) {
                // hirst half
                test[i][j] = elevationData[i][j];
                testInverse[i][j] = HMConstants.doubleNovalue;
            } else {
                test[i][j] = HMConstants.doubleNovalue;
                testInverse[i][j] = elevationData[i][j];
            }
        }
    }

    OmsRasterVectorIntersector intersect = new OmsRasterVectorIntersector();
    intersect.inRaster = elevationCoverage;
    intersect.inVector = testLeftFC;
    intersect.process();
    GridCoverage2D outRaster = intersect.outRaster;
    checkMatrixEqual(outRaster.getRenderedImage(), test);

    intersect = new OmsRasterVectorIntersector();
    intersect.inRaster = elevationCoverage;
    intersect.inVector = testLeftFC;
    intersect.doInverse = true;
    intersect.process();
    outRaster = intersect.outRaster;
    checkMatrixEqual(outRaster.getRenderedImage(), testInverse);
}
 
Example 24
Source Project: hortonmachine   Source File: TestGc.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("nls")
public void testGc() {
    HashMap<String, Double> envelopeParams = HMTestMaps.getEnvelopeparams();
    CoordinateReferenceSystem crs = HMTestMaps.getCrs();

    double[][] slopeData = HMTestMaps.slopeData;
    double[][] networkData = HMTestMaps.extractNet1Data;
    double[][] cp9Data = HMTestMaps.cp9Data;

    GridCoverage2D slopeGC = CoverageUtilities.buildCoverage("slope", slopeData, envelopeParams, crs, true);
    GridCoverage2D networkGC = CoverageUtilities.buildCoverage("net", networkData, envelopeParams, crs, true);
    GridCoverage2D cp9GC = CoverageUtilities.buildCoverage("cp9", cp9Data, envelopeParams, crs, true);

    OmsGc gc = new OmsGc();
    gc.inSlope = slopeGC;
    gc.inNetwork = networkGC;
    gc.inCp9 = cp9GC;
    gc.pTh=7;
    gc.process();
    
    GridCoverage2D outGCClasses= gc.outClasses;
    GridCoverage2D outGcAggregate = gc.outAggregateClasses;

    checkMatrixEqual(outGCClasses.getRenderedImage(), HMTestMaps.cp9GCData);
    checkMatrixEqual(outGcAggregate.getRenderedImage(), HMTestMaps.cp3GCData);

}
 
Example 25
/**
 * Transform a {@link Envelope} from the source to the target CRS.
 *
 * @param source source geometry
 * @param sourceCrs source CRS
 * @param targetCrs target CRS
 * @return transformed source, now in target CRS
 * @throws GeomajasException building the transformation or doing the transformation is not possible
 */
public Envelope transform(Envelope source, CoordinateReferenceSystem sourceCrs, CoordinateReferenceSystem targetCrs)
		throws GeomajasException {
	if (sourceCrs == targetCrs) { // NOPMD
		// only works when the caching of the CRSs works
		return source;
	}

	CrsTransform crsTransform = geoService.getCrsTransform(sourceCrs, targetCrs);
	return geoService.transform(source, crsTransform);
}
 
Example 26
/**
 * Creates a {@link GridCoverage2D coverage} from the {@link RenderedImage image} and the necessary geographic Information.
 * 
 * @param name the name of the coverage.
 * @param renderedImage the image containing the data.
 * @param envelopeParams the map of boundary parameters.
 * @param crs the {@link CoordinateReferenceSystem}.
 * @return the {@link GridCoverage2D coverage}.
 */
public static GridCoverage2D buildCoverage( String name, RenderedImage renderedImage, HashMap<String, Double> envelopeParams,
        CoordinateReferenceSystem crs ) {

    double west = envelopeParams.get(WEST);
    double south = envelopeParams.get(SOUTH);
    double east = envelopeParams.get(EAST);
    double north = envelopeParams.get(NORTH);
    Envelope2D writeEnvelope = new Envelope2D(crs, west, south, east - west, north - south);
    GridCoverageFactory factory = CoverageFactoryFinder.getGridCoverageFactory(null);

    GridCoverage2D coverage2D = factory.create(name, renderedImage, writeEnvelope);
    return coverage2D;
}
 
Example 27
Source Project: sis   Source File: CRSPair.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@code CRSPair} for the specified source and target CRS.
 */
CRSPair(final CoordinateReferenceSystem sourceCRS,
        final CoordinateReferenceSystem targetCRS)
{
    this.sourceCRS = sourceCRS;
    this.targetCRS = targetCRS;
}
 
Example 28
private void checkMarino() throws Exception {
	CoordinateReferenceSystem crs = beanLayer.getCrs();
	Envelope envelope;
	recorder.clear();
	envelope = layerService.getBounds(LAYER_ID, crs, null);
	junit.framework.Assert.assertEquals(2, envelope.getMinX(), ALLOWANCE);
	junit.framework.Assert.assertEquals(0, envelope.getMinY(), ALLOWANCE);
	junit.framework.Assert.assertEquals(7, envelope.getMaxX(), ALLOWANCE);
	junit.framework.Assert.assertEquals(3, envelope.getMaxY(), ALLOWANCE);
}
 
Example 29
@Execute
public void process() throws Exception {

    // Creates the output points hashmap
    LinkedHashMap<SimpleFeature, double[]> allNetPointsMap = new LinkedHashMap<SimpleFeature, double[]>();

    CoordinateReferenceSystem crs = inNetPoints.getBounds().getCoordinateReferenceSystem();

    // Insert the points in the final hashmap
    List<SimpleFeature> netFeatures = FeatureUtilities.featureCollectionToList(inNetPoints);
    netFeatures.sort(new Comparator<SimpleFeature>(){
        public int compare( SimpleFeature o1, SimpleFeature o2 ) {
            int i1 = ((Number) o1.getAttribute(LWFields.LINKID)).intValue();
            int i2 = ((Number) o2.getAttribute(LWFields.LINKID)).intValue();
            if (i1 < i2) {
                return -1;
            } else if (i1 > i2) {
                return 1;
            }
            return 0;
        }
    });
    for( SimpleFeature netFeature : netFeatures ) {
        allNetPointsMap.put(netFeature, new double[NEW_NETWORK_ATTRIBUTES_NUM]);
    }

    // Generates supporting variables
    LinkedHashMap<SimpleFeature, String> problemPointsMap = new LinkedHashMap<SimpleFeature, String>();
    LinkedHashMap<SimpleFeature, double[]> validPointsMap = new LinkedHashMap<SimpleFeature, double[]>();
    ConcurrentLinkedQueue<Object[]> validPointsLineList = new ConcurrentLinkedQueue<Object[]>();
    handleChannelEdited(inBankfull, allNetPointsMap, validPointsMap, problemPointsMap, validPointsLineList);

    outNetPoints = getNetworkPoints(crs, validPointsMap);
    outBankfullSections = getWidthLines(crs, validPointsLineList);
    outProblemPoints = getProblemPoints(crs, problemPointsMap);

}
 
Example 30
Source Project: geowave   Source File: PolygonAreaCalculator.java    License: 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;
}