Java Code Examples for org.geotools.referencing.crs.DefaultGeographicCRS

The following are top voted examples for showing how to use org.geotools.referencing.crs.DefaultGeographicCRS. 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: hortonmachine   File: DaoImages.java   View source code 7 votes vote down vote up
/**
 * Get the current data envelope.
 * 
 * @param connection the db connection.
 * @return the envelope.
 * @throws Exception
 */
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception {
    String query = "SELECT min(" + //
            ImageTableFields.COLUMN_LON.getFieldName() + "), max(" + //
            ImageTableFields.COLUMN_LON.getFieldName() + "), min(" + //
            ImageTableFields.COLUMN_LAT.getFieldName() + "), max(" + //
            ImageTableFields.COLUMN_LAT.getFieldName() + ") " + //
            " FROM " + TABLE_IMAGES;
    try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) {
        if (rs.next()) {
            double minX = rs.getDouble(1);
            double maxX = rs.getDouble(2);
            double minY = rs.getDouble(3);
            double maxY = rs.getDouble(4);

            ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84);
            return env;
        }
    }

    return null;
}
 
Example 2
Project: hortonmachine   File: RasterizedSpatialiteLasLayer.java   View source code 7 votes vote down vote up
public RasterizedSpatialiteLasLayer( String title, ASpatialDb db, Integer tileSize, boolean transparentBackground,
        boolean doIntensity ) throws Exception {
    super(makeLevels(title, tileSize, transparentBackground, db, doIntensity));
    String plus = doIntensity ? INTENSITY : ELEVATION;
    this.layerName = title + " " + plus;
    this.setUseTransparentTextures(true);

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

        centre = envLL.centre();
    } catch (Exception e) {
        e.printStackTrace();
        centre = CrsUtilities.WORLD.centre();
    }
}
 
Example 3
Project: snap-desktop   File: FeatureLayer.java   View source code 7 votes vote down vote up
public FeatureLayer(LayerType layerType, final FeatureCollection<SimpleFeatureType, SimpleFeature> fc,
                    PropertySet configuration) {
    super(layerType, configuration);
    crs = fc.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem();
    if (crs == null) {
        // todo - check me! Why can this happen??? (nf)
        crs = DefaultGeographicCRS.WGS84;
    }
    final ReferencedEnvelope envelope = new ReferencedEnvelope(fc.getBounds(), crs);
    modelBounds = new Rectangle2D.Double(envelope.getMinX(), envelope.getMinY(),
                                         envelope.getWidth(), envelope.getHeight());
    mapContext = new DefaultMapContext(crs);
    final Style style = (Style) configuration.getValue(FeatureLayerType.PROPERTY_NAME_SLD_STYLE);
    mapContext.addLayer(fc, style);
    renderer = new StreamingRenderer();
    workaroundLabelCacheBug();
    style.accept(new RetrievingStyleVisitor());
    renderer.setContext(mapContext);

}
 
Example 4
Project: sldeditor   File: WKTConversion.java   View source code 6 votes vote down vote up
/**
 * Initialise the WKTParser object.
 */
private static void initialise() {
    Hints hints = new Hints(Hints.CRS, DefaultGeographicCRS.WGS84);

    PositionFactory positionFactory = GeometryFactoryFinder.getPositionFactory(hints);
    GeometryFactory geometryFactory = GeometryFactoryFinder.getGeometryFactory(hints);
    PrimitiveFactory primitiveFactory = GeometryFactoryFinder.getPrimitiveFactory(hints);
    AggregateFactory aggregateFactory = GeometryFactoryFinder.getAggregateFactory(hints);

    wktParser = new WKTParser(geometryFactory, primitiveFactory, positionFactory,
            aggregateFactory);

    wktTypeList.add(new WKTType(WKT_POINT, false, 1, "Point", false, false));
    wktTypeList.add(new WKTType(WKT_MULTIPOINT, true, 1, "Point", true, false));
    wktTypeList.add(new WKTType(WKT_LINESTRING, false, 2, "Line", false, false));
    wktTypeList.add(new WKTType("LINEARRING", false, 2, "Line", false, false));
    wktTypeList.add(new WKTType(WKT_MULTILINESTRING, true, 2, "Line", true, false));
    wktTypeList.add(new WKTType(WKT_POLYGON, false, -1, "Polygon", false, true));
    wktTypeList.add(new WKTType(WKT_MULTIPOLYGON, true, -1, "Polygon", true, true));

    for (WKTType wkyType : wktTypeList) {
        wktTypeMap.put(wkyType.getName(), wkyType);
    }
}
 
Example 5
Project: osmosis-nls-dem   File: NLSDEMTask.java   View source code 6 votes vote down vote up
public NLSDEMTask(String apiKey, URI prjFileLocation, String tiffStorage) throws URISyntaxException {
    if (prjFileLocation == null)
        // Fallback to EPSG3067 found within JAR
        prjFileLocation = NLSDEMTask.class.getResource("EPSG3067.prj").toURI();

    if (tiffStorage == null)
        tiffStorage = System.getProperty("java.io.tmpdir");

    Path prjFile = Paths.get(prjFileLocation);
    if (!Files.isReadable(prjFile))
        throw new IllegalArgumentException(
                ".prj file " + prjFileLocation + " cannot be read. See that it exists and is readable!");

    this.sourceCRS = DefaultGeographicCRS.WGS84;
    try {
        PrjFileReader reader = new PrjFileReader(FileChannel.open(prjFile, StandardOpenOption.READ));
        targetCRS = reader.getCoordinateReferenceSystem();
        transform = CRS.findMathTransform(sourceCRS, targetCRS);
    } catch (FactoryException | IOException e) {
        throw new IllegalArgumentException(".prj file provided is invalid!", e);
    }
    this.nlsXmlClient = new NLSXMLClient(apiKey, tiffStorage);
    this.tiffDownloaderService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(),
            new NLSTiffDownloaderFactory());
}
 
Example 6
Project: fhaes   File: Csv2Shape2.java   View source code 6 votes vote down vote up
/**
 * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile dynamically.
 * <p>
 * This method is an improvement on the code used in the main method above (where we used DataUtilities.createFeatureType) because we
 * can set a Coordinate Reference System for the FeatureType and a a maximum field length for the 'name' field dddd
 */
private static SimpleFeatureType createFeatureType() {
	
	SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
	builder.setName("Location");
	builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
	
	// add attributes in order
	builder.add("the_geom", Point.class);
	builder.length(15).add("Name", String.class); // <- 15 chars width for name field
	
	// build the type
	final SimpleFeatureType LOCATION = builder.buildFeatureType();
	
	return LOCATION;
}
 
Example 7
Project: fhaes   File: Csv2Shape.java   View source code 6 votes vote down vote up
/**
 * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile dynamically.
 * <p>
 * This method is an improvement on the code used in the main method above (where we used DataUtilities.createFeatureType) because we
 * can set a Coordinate Reference System for the FeatureType and a a maximum field length for the 'name' field dddd
 */
@SuppressWarnings("unused")
private static SimpleFeatureType createFeatureType() {
	
	SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
	builder.setName("Location");
	builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
	
	// add attributes in order
	builder.add("Location", Point.class);
	builder.length(15).add("Name", String.class); // <- 15 chars width for name field
	
	// build the type
	final SimpleFeatureType LOCATION = builder.buildFeatureType();
	
	return LOCATION;
}
 
Example 8
Project: fhaes   File: ShapeFileDialog.java   View source code 6 votes vote down vote up
private static SimpleFeatureType createFeatureType(List<Integer> years) {

	SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
	builder.setName("FHAES");
	builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
	
	// add attributes in order
	builder.add("the_geom", Point.class);
	builder.add("name", String.class);
	for (Integer i : years)
	{
		builder.add(i + "", Integer.class);
	}
	
	// build the type
	final SimpleFeatureType FHAES = builder.buildFeatureType();
	
	return FHAES;
}
 
Example 9
Project: fhaes   File: ShapeFileDialog.java   View source code 6 votes vote down vote up
private static SimpleFeatureType createStyle2FeatureType() {

	SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
	builder.setName("FHAES");
	builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system
	
	// add attributes in order
	builder.add("the_geom", Point.class);
	builder.add("name", String.class);
	builder.add("year", Integer.class);
	builder.add("value", Integer.class);
	
	// build the type
	final SimpleFeatureType FHAES = builder.buildFeatureType();
	
	return FHAES;
}
 
Example 10
Project: garmin-fit-geojson   File: GarminFitService.java   View source code 6 votes vote down vote up
/**
 * The purpose of this method is to generate the schema definition for the GeoJSON.
 * @return SimpleFeatureType defining the the feature properties.
 */
public SimpleFeatureType getFeatureSchema() {
    final SimpleFeatureTypeBuilder simpleFeatureType = new SimpleFeatureTypeBuilder();
    simpleFeatureType.add("geom", LineString.class, DefaultGeographicCRS.WGS84);
    simpleFeatureType.add("name", String.class);
    simpleFeatureType.add("activityId", Long.class);
    simpleFeatureType.setName("activity");
    simpleFeatureType.add("name", String.class);
    simpleFeatureType.add("sport", String.class);
    simpleFeatureType.add("startTime", String.class);
    simpleFeatureType.add("totalMeters", Double.class);
    simpleFeatureType.add("totalSeconds", Double.class);
    simpleFeatureType.add("minLat", Double.class);
    simpleFeatureType.add("minLon", Double.class);
    simpleFeatureType.add("maxLat", Double.class);
    simpleFeatureType.add("maxLon", Double.class);
    return simpleFeatureType.buildFeatureType();
}
 
Example 11
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 12
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 13
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 14
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 15
Project: osmgpxfilter   File: ShapeFileWriter.java   View source code 6 votes vote down vote up
private SimpleFeatureType createFeatureType() {

		SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
		builder.setName("GPX");
		builder.setCRS(DefaultGeographicCRS.WGS84);

		// add attributes in order
		builder.add("the_geom", Point.class);
		builder.add("gpx_id", Integer.class);
		builder.add("trk_id", Integer.class);
		builder.add("seg_id", Integer.class);
		builder.add("trkpt_id", Integer.class);
		builder.add("timestamp", String.class);
		builder.add("ele", Double.class);

		return builder.buildFeatureType();
	}
 
Example 16
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 17
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 18
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 19
Project: elasticgeo   File: GeoHashGridProcessTest.java   View source code 6 votes vote down vote up
@Test
public void testSubCellCropWithSheer() throws NoSuchAuthorityCodeException, TransformException, FactoryException {
    ReferencedEnvelope envelope = new ReferencedEnvelope(-168.75,168.75,-78.75,78.75,DefaultGeographicCRS.WGS84);
    int width = 900;
    int height = 600;
    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);
}
 
Example 20
Project: elasticgeo   File: GeoHashGridTest.java   View source code 6 votes vote down vote up
@Test
public void testGeoHashGrid() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    float[][] expected = new float[ny][nx];
    expected[ny-1][0] = 10;
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    IntStream.range(0, ny).forEach(i->assertTrue(Arrays.equals(expected[i], geohashGrid.getGrid()[i])));
}
 
Example 21
Project: elasticgeo   File: GeoHashGridTest.java   View source code 6 votes vote down vote up
@Test
public void testGeoHashGrid_scaled() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",20))),
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(89.9,179.9),1),"doc_count",30)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.setScale(new RasterScale(5f, 10f));
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    float[][] expected = new float[ny][nx];
    expected[0][7] = 10;
    expected[ny-1][0] = 5;
    IntStream.range(0, ny).forEach(i->assertTrue(Arrays.equals(geohashGrid.getGrid()[i], expected[i])));
}
 
Example 22
Project: s2tbx   File: S2tbxMosaicOp.java   View source code 6 votes vote down vote up
/**
 * STEP 3 methods
 */

private ReferencedEnvelope computeMosaicBounds() {
    final Rectangle2D initialBounds = new Rectangle2D.Double();
    initialBounds.setFrameFromDiagonal(this.westBound, this.southBound, this.eastBound, this.northBound);
    final ReferencedEnvelope boundsEnvelope = new ReferencedEnvelope(initialBounds, DefaultGeographicCRS.WGS84);
    try {
        return boundsEnvelope.transform(this.targetCRS, true);
    } catch (TransformException | FactoryException e) {
        throw new OperatorException(e);
    }
}
 
Example 23
Project: s2tbx   File: JP2ProductWriterPluginTest.java   View source code 6 votes vote down vote up
@Test
public void testEncodingQualification() throws Exception {
    Product product = new Product("Name", "JP2", 4, 4);

    EncodeQualification encodeQualification = plugIn.getEncodeQualification(product);
    assertNotNull(encodeQualification);
    assertEquals(EncodeQualification.Preservation.PARTIAL, encodeQualification.getPreservation());
    assertNotNull(encodeQualification.getInfoString());

    TiePointGrid lat = new TiePointGrid("lat", 4, 4, 0, 0, 1, 1, new float[16]);
    TiePointGrid lon = new TiePointGrid("lon", 4, 4, 0, 0, 1, 1, new float[16]);
    product.addTiePointGrid(lat);
    product.addTiePointGrid(lon);
    product.setSceneGeoCoding(new TiePointGeoCoding(lat, lon));
    encodeQualification = plugIn.getEncodeQualification(product);
    assertEquals(EncodeQualification.Preservation.PARTIAL, encodeQualification.getPreservation());
    assertNotNull(encodeQualification.getInfoString());

    product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 4, 4, 0, 0, 1, 1));
    encodeQualification = plugIn.getEncodeQualification(product);
    assertEquals(EncodeQualification.Preservation.FULL, encodeQualification.getPreservation());
}
 
Example 24
Project: georefine   File: CreatePoint.java   View source code 6 votes vote down vote up
public Object call(Properties bindings, Object[] args) {
    if(args.length==2){
        String lat = args[0].toString();
        String lng = args[1].toString();

        double[] latlng = {
            Double.parseDouble(lat),
            Double.parseDouble(lng)
        };
        
        GeometryBuilder builder = new GeometryBuilder(DefaultGeographicCRS.WGS84);
        
        return JTS.toGeometry(builder.createPoint(latlng).getDirectPosition());
    }
    return new EvalError(ControlFunctionRegistry.getFunctionName(this) + " expects 2 arguments");
}
 
Example 25
Project: soil_sealing   File: SoilSealingCLCProcess.java   View source code 6 votes vote down vote up
/**
 * Here is how you can use a SimpleFeatureType builder to create the schema for your shapefile
 * dynamically.
 * <p>
 * This method is an improvement on the code used in the main method above (where we used
 * DataUtilities.createFeatureType) because we can set a Coordinate Reference System for the
 * FeatureType and a a maximum field length for the 'name' field
 */
private static SimpleFeatureType createFeatureType(String name) {

    SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName(name);
    builder.setCRS(DefaultGeographicCRS.WGS84); // <- Coordinate reference system

    // add attributes in order
    builder.add("the_geom", MultiPolygon.class);
    builder.length(50).add("au_name", String.class); // <- 15 chars width for name field
    builder.add("value", Double.class);
    builder.add("legend", Double.class);
    
    // build the type
    final SimpleFeatureType SOIL_INDEX_TYPE = builder.buildFeatureType();

    return SOIL_INDEX_TYPE;
}
 
Example 26
Project: risky   File: AnimatorPreferences.java   View source code 6 votes vote down vote up
public static ReferencedEnvelope restoreBounds(double defaultX1, double defaultX2,
        double defaultY1, double defaultY2, Window window, Animator animator) {
    Preferences prefs = Preferences.userNodeForPackage(Animator.class);
    double x1 = Double.parseDouble(prefs.get("bounds.x1", defaultX1 + ""));
    double x2 = Double.parseDouble(prefs.get("bounds.x2", defaultX2 + ""));
    double y1 = Double.parseDouble(prefs.get("bounds.y1", defaultY1 + ""));
    double y2 = Double.parseDouble(prefs.get("bounds.y2", defaultY2 + ""));
    window.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            ReferencedEnvelope bounds = animator.getBounds();
            prefs.put("bounds.x1", bounds.getMinX() + "");
            prefs.put("bounds.x2", bounds.getMaxX() + "");
            prefs.put("bounds.y1", bounds.getMinY() + "");
            prefs.put("bounds.y2", bounds.getMaxY() + "");
        }

    });
    return new ReferencedEnvelope(x1, x2, y1, y2, DefaultGeographicCRS.WGS84);
}
 
Example 27
Project: risky   File: Map.java   View source code 6 votes vote down vote up
private static Layer createExtraFeatures() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("Location");
    b.setCRS(DefaultGeographicCRS.WGS84);
    // picture location
    b.add("geom", Point.class);
    final SimpleFeatureType TYPE = b.buildFeatureType();

    GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
    Point point = gf.createPoint(new Coordinate(CANBERRA_LONG, CANBERRA_LAT));

    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(TYPE);
    builder.add(point);
    SimpleFeature feature = builder.buildFeature("Canberra");
    DefaultFeatureCollection features = new DefaultFeatureCollection(null, null);
    features.add(feature);

    Style style = SLD.createPointStyle("Star", Color.BLUE, Color.BLUE, 0.3f, 10);

    return new FeatureLayer(features, style);
}
 
Example 28
Project: hortonmachine   File: MBTilesHelper.java   View source code 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 29
Project: hortonmachine   File: CoverageUtilities.java   View source code 6 votes vote down vote up
/**
 * Creates a useless {@link GridCoverage2D} that might be usefull as placeholder.
 * 
 * @return the dummy grod coverage.
 */
public static GridCoverage2D buildDummyCoverage() {
    HashMap<String, Double> envelopeParams = new HashMap<String, Double>();
    envelopeParams.put(NORTH, 1.0);
    envelopeParams.put(SOUTH, 0.0);
    envelopeParams.put(WEST, 0.0);
    envelopeParams.put(EAST, 1.0);
    envelopeParams.put(XRES, 1.0);
    envelopeParams.put(YRES, 1.0);
    envelopeParams.put(ROWS, 1.0);
    envelopeParams.put(COLS, 1.0);
    double[][] dataMatrix = new double[1][1];
    dataMatrix[0][0] = 0;
    WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, true);
    return buildCoverage("dummy", writableRaster, envelopeParams, DefaultGeographicCRS.WGS84); //$NON-NLS-1$
}
 
Example 30
Project: hortonmachine   File: OmsNmeaFeatureReader.java   View source code 6 votes vote down vote up
public static SimpleFeatureBuilder getNmeaFeatureBuilder() {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("nmea");
    b.setCRS(DefaultGeographicCRS.WGS84);
    b.add("the_geom", Point.class);
    b.add(NmeaGpsPoint.strSpeed, Double.class);
    b.add(NmeaGpsPoint.strAltitude, Double.class);
    b.add(NmeaGpsPoint.strQuality, Double.class);
    b.add(NmeaGpsPoint.strSat, Integer.class);
    b.add(NmeaGpsPoint.strHdop, Double.class);
    b.add(NmeaGpsPoint.strMsl, Double.class);
    b.add(NmeaGpsPoint.strUtctime, String.class);
    b.add(NmeaGpsPoint.strMag_var, Double.class);
    b.add(NmeaGpsPoint.strAngle, Double.class);
    final SimpleFeatureType featureType = b.buildFeatureType();
    SimpleFeatureBuilder nmeaSimpleFeatureBuilder = new SimpleFeatureBuilder(featureType);
    return nmeaSimpleFeatureBuilder;
}
 
Example 31
Project: hortonmachine   File: DaoGpsLog.java   View source code 6 votes vote down vote up
/**
 * Get the current data envelope.
 * 
 * @param connection the db connection.
 * @return the envelope.
 * @throws Exception
 */
public static ReferencedEnvelope getEnvelope( IHMConnection connection ) throws Exception {
    String query = "SELECT min(" + //
            GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), max(" + //
            GpsLogsDataTableFields.COLUMN_DATA_LON.getFieldName() + "), min(" + //
            GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + "), max(" + //
            GpsLogsDataTableFields.COLUMN_DATA_LAT.getFieldName() + ") " + //
            " FROM " + TABLE_GPSLOG_DATA;
    try (IHMStatement statement = connection.createStatement(); IHMResultSet rs = statement.executeQuery(query);) {
        if (rs.next()) {
            double minX = rs.getDouble(1);
            double maxX = rs.getDouble(2);
            double minY = rs.getDouble(3);
            double maxY = rs.getDouble(4);

            ReferencedEnvelope env = new ReferencedEnvelope(minX, maxX, minY, maxY, DefaultGeographicCRS.WGS84);
            return env;
        }
    }

    return null;
}
 
Example 32
Project: hortonmachine   File: TestENU.java   View source code 6 votes vote down vote up
public void testWithGeotools() throws MatrixException {
    Coordinate c1 = new Coordinate(11, 46, 0);
    Coordinate c2 = new Coordinate(11.001, 46.001, 0);

    GeodeticCalculator gc = new GeodeticCalculator(DefaultGeographicCRS.WGS84);
    gc.setStartingGeographicPoint(c1.x, c1.y);
    gc.setDestinationGeographicPoint(c2.x, c2.y);
    double orthodromicDistance = gc.getOrthodromicDistance();

    ENU enu = new ENU(c1);
    Coordinate ce1 = enu.wgs84ToEnu(c1);
    Coordinate ce2 = enu.wgs84ToEnu(c2);

    double distance = ce1.distance(ce2);
    assertTrue(isDeltaOk(orthodromicDistance, distance));
    
    Coordinate c1Back = enu.enuToWgs84(ce1);
    Coordinate c2Back = enu.enuToWgs84(ce2);
    
    assertEquals(0, c1.distance(c1Back), 0.000001);
    assertEquals(0, c2.distance(c2Back), 0.000001);
    
}
 
Example 33
Project: hortonmachine   File: TestFeatureUtils.java   View source code 6 votes vote down vote up
@SuppressWarnings("nls")
public void testFeatureUtils() throws Exception {
    SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
    b.setName("typename");
    b.setCRS(DefaultGeographicCRS.WGS84);
    b.add("the_geom", Point.class);
    b.add("AttrName", String.class);
    SimpleFeatureType type = b.buildFeatureType();
    SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
    Object[] values = new Object[]{GeometryUtilities.gf().createPoint(new Coordinate(0, 0)), "test"};
    builder.addAll(values);
    SimpleFeature feature = builder.buildFeature(type.getTypeName());

    Object attr = FeatureUtilities.getAttributeCaseChecked(feature, "attrname");
    assertEquals("test", attr.toString());
    attr = FeatureUtilities.getAttributeCaseChecked(feature, "attrnam");
    assertNull(attr);
}
 
Example 34
Project: hortonmachine   File: RL2NwwLayer.java   View source code 6 votes vote down vote up
public RL2NwwLayer( RL2CoverageHandler rl2Handler, Integer tileSize ) throws Exception {
    super(makeLevels(rl2Handler, tileSize));
    RasterCoverage rasterCoverage = rl2Handler.getRasterCoverage();
    this.layerName = rasterCoverage.coverage_name;

    double w = rasterCoverage.extent_minx;
    double s = rasterCoverage.extent_miny;
    double e = rasterCoverage.extent_maxx;
    double n = rasterCoverage.extent_maxy;

    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.srid);

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
    centerCoordinateLL = JTS.transform(centerCoordinate, null, transform);

    this.setUseTransparentTextures(true);

}
 
Example 35
Project: hortonmachine   File: ImageMosaicNwwLayer.java   View source code 6 votes vote down vote up
public ImageMosaicNwwLayer( File imageMosaicShpFile, Integer tileSize, GeneralParameterValue[] gp,
        boolean removeSameColorImages ) throws Exception {
    super(makeLevels(imageMosaicShpFile, getRenderer(imageMosaicShpFile, gp), tileSize, removeSameColorImages));
    this.layerName = FileUtilities.getNameWithoutExtention(imageMosaicShpFile);

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

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

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

    centerCoordinate = new Coordinate(centerX, centerY);

    this.setUseTransparentTextures(true);

}
 
Example 36
Project: hortonmachine   File: NwwPanel.java   View source code 6 votes vote down vote up
public ReferencedEnvelope getViewportBounds() {
    View view = wwd.getView();
    Position posUL = view.computePositionFromScreenPoint(0, 0);
    Position posLR = view.computePositionFromScreenPoint(getWidth(), getHeight());

    if (posLR != null && posUL != null) {
        double west = posUL.longitude.degrees;
        double north = posUL.latitude.degrees;
        double east = posLR.longitude.degrees;
        double south = posLR.latitude.degrees;

        ReferencedEnvelope env = new ReferencedEnvelope(west, east, south, north, DefaultGeographicCRS.WGS84);
        return env;
    } else {
        return null;// new ReferencedEnvelope(-180, 180, -90, 90,
                    // DefaultGeographicCRS.WGS84);
    }
}
 
Example 37
Project: gt-jdbc-monetdb-simple   File: SimpleMonetDBFeatureReader.java   View source code 6 votes vote down vote up
public SimpleMonetDBFeatureReader(String sql, Connection conn, SimpleMonetDBFeatureSource featureSource, SimpleFeatureType featureType, Hints hints, int srid ) 
throws SQLException {
    init( featureSource, featureType, hints );
    
    this.srid = srid;
    
    CoordinateReferenceSystem sourceCrs = featureType.getGeometryDescriptor().getCoordinateReferenceSystem();
    CoordinateReferenceSystem targetCrs = DefaultGeographicCRS.WGS84;
    try {
        targetCrs = CRS.decode("EPSG:3857");
        boolean lenient = true;
        mathTransform = CRS.findMathTransform(sourceCrs, targetCrs, lenient);
    } catch (Exception ex) {
        Logger.getLogger(SimpleMonetDBFeatureReader.class.getName()).log(Level.SEVERE, null, ex);
    }
    
    //create the result set
    this.conn = conn;
    st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    rs = st.executeQuery(sql);
}
 
Example 38
Project: uDig-WPS-plugin   File: WPSGeoResourceImpl.java   View source code 6 votes vote down vote up
public ReferencedEnvelope getBounds(){
        	if (this.bounds != null) {
        		return bounds;
        	}
//    		ATTENTION: the featureReader is retrieved per process not per output! So always the same featureReader for multiple outputs
    		WPSFeatureReader fr = null;
			try {
				fr = (WPSFeatureReader)parent.getDS(null).getFeatureReader(new DefaultQuery(process.getUniqueIdentifier()), null);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				WPSPlugin.log("Error occured retrieving BBOX", e);
			}
			if(fr == null) {
				return null;
			}
    		Envelope extent = fr.getBounds();
    		if(crs != null) {
    			this.bounds  = new ReferencedEnvelope(extent,crs);
    		}
    		else{
    			this.bounds = new ReferencedEnvelope(extent, DefaultGeographicCRS.WGS84);
    		}
    		return bounds;
        }
 
Example 39
Project: snap-desktop   File: ImportTrackAction.java   View source code 6 votes vote down vote up
private static SimpleFeatureType createTrackFeatureType(GeoCoding geoCoding) {
    SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
    ftb.setName("org.esa.snap.TrackPoint");
    /*0*/
    ftb.add("pixelPos", Point.class, geoCoding.getImageCRS());
    /*1*/
    ftb.add("geoPos", Point.class, DefaultGeographicCRS.WGS84);
    /*2*/
    ftb.add("data", Double.class);
    ftb.setDefaultGeometry(geoCoding instanceof CrsGeoCoding ? "geoPos" : "pixelPos");
    // GeoTools Bug: this doesn't work
    // ftb.userData("trackPoints", "true");
    final SimpleFeatureType ft = ftb.buildFeatureType();
    ft.getUserData().put("trackPoints", "true");
    return ft;
}
 
Example 40
Project: snap-desktop   File: AbstractImportVectorDataNodeAction.java   View source code 6 votes vote down vote up
@Override
public CoordinateReferenceSystem getFeatureCrs(final Product product) {
    if (product.getSceneCRS() == Product.DEFAULT_IMAGE_CRS) {
        return Product.DEFAULT_IMAGE_CRS;
    }

    final CoordinateReferenceSystem[] featureCrsBuffer = new CoordinateReferenceSystem[1];
    Runnable runnable = () -> featureCrsBuffer[0] = promptForFeatureCrs(product);
    if (!SwingUtilities.isEventDispatchThread()) {
        try {
            SwingUtilities.invokeAndWait(runnable);
        } catch (InterruptedException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    } else {
        runnable.run();
    }
    CoordinateReferenceSystem featureCrs = featureCrsBuffer[0];
    return featureCrs != null ? featureCrs : DefaultGeographicCRS.WGS84;
}