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

The following examples show how to use org.geotools.referencing.CRS#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OutputGeometryForm.java    From snap-desktop with GNU General Public License v3.0 8 votes vote down vote up
public static void main(String[] args) throws Exception {
    final JFrame jFrame = new JFrame("Output parameter Definition Form");
    Container contentPane = jFrame.getContentPane();
    if (args.length == 0) {
        throw new IllegalArgumentException("Missing argument to product file.");
    }
    Product sourceProduct = ProductIO.readProduct(args[0]);
    CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:32632");
    OutputGeometryFormModel model = new OutputGeometryFormModel(sourceProduct, targetCrs);
    OutputGeometryForm form = new OutputGeometryForm(model);
    contentPane.add(form);

    jFrame.setSize(400, 600);
    jFrame.setLocationRelativeTo(null);
    jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            jFrame.setVisible(true);
        }
    });
}
 
Example 2
Source File: PolygonAreaCalculator.java    From geowave with Apache License 2.0 6 votes vote down vote up
private CoordinateReferenceSystem lookupUtmCrs(final double centerLat, final double centerLon)
    throws NoSuchAuthorityCodeException, FactoryException {
  final int epsgCode =
      (32700 - (Math.round((45f + (float) centerLat) / 90f) * 100))
          + Math.round((183f + (float) centerLon) / 6f);

  final String crsId = "EPSG:" + Integer.toString(epsgCode);

  CoordinateReferenceSystem crs = crsMap.get(crsId);

  if (crs == null) {
    crs = CRS.decode(crsId, true);

    crsMap.put(crsId, crs);
  }

  return crs;
}
 
Example 3
Source File: OrthodromicDistancePartitioner.java    From geowave with Apache License 2.0 6 votes vote down vote up
private GeometryCalculations getCalculator() {
  if (calculator == null) {
    // this block would only occur in test or in failed initialization
    if (crs == null) {
      try {
        crs = CRS.decode(crsName, true);
      } catch (final FactoryException e) {
        LOGGER.error("CRS not providd and default EPSG:4326 cannot be instantiated", e);
        throw new RuntimeException(e);
      }
    }

    calculator = new GeometryCalculations(crs);
  }
  return calculator;
}
 
Example 4
Source File: CustomCrsIndexModel.java    From geowave with Apache License 2.0 5 votes vote down vote up
public CoordinateReferenceSystem getCrs() {
  if (crs == null) {
    try {
      crs = CRS.decode(crsCode, true);
    } catch (final FactoryException e) {
      LOGGER.warn("Unable to decode indexed crs", e);
    }
  }
  return crs;
}
 
Example 5
Source File: OrthodromicDistancePartitioner.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(final ScopedJobConfiguration config) throws IOException {

  crsName = config.getString(GlobalParameters.Global.CRS_ID, "EPSG:4326");
  try {
    crs = CRS.decode(crsName, true);
  } catch (final FactoryException e) {
    throw new IOException("Cannot find CRS " + crsName, e);
  }

  try {
    dimensionExtractor =
        config.getInstance(
            ExtractParameters.Extract.DIMENSION_EXTRACT_CLASS,
            DimensionExtractor.class,
            SimpleFeatureGeometryExtractor.class);
  } catch (final Exception ex) {
    throw new IOException(
        "Cannot find class for  " + ExtractParameters.Extract.DIMENSION_EXTRACT_CLASS.toString(),
        ex);
  }

  final String distanceUnit =
      config.getString(PartitionParameters.Partition.GEOMETRIC_DISTANCE_UNIT, "m");

  this.geometricDistanceUnit = GeometryUtils.lookup(distanceUnit);

  super.initialize(config);
}
 
Example 6
Source File: WmsWrapper.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static void main( String[] args ) throws Exception {
    String url = "https://gis.stmk.gv.at/arcgis/services/OGD/als_schummerung/MapServer/WmsServer?request=GetCapabilities&service=WMS";
    String wmscode = "EPSG:4326";
    int width = 1000;
    int height = 1000;
    String outputImage = "/home/hydrologis/TMP/VIENNA/wms.png";

    WmsWrapper ww = new WmsWrapper(url);
    ww.printInfo();
    Layer[] layers = ww.getLayers();
    for( Layer layer : layers ) {
        String name = layer.getName();
        if (name.equals("Digitales_Oberflaechenmodell_DOM")) {
            CRSEnvelope latLonBoundingBox = layer.getLatLonBoundingBox();
            double w = latLonBoundingBox.getMinX();
            double e = latLonBoundingBox.getMaxX();
            double s = latLonBoundingBox.getMinY();
            double n = latLonBoundingBox.getMaxY();
            ReferencedEnvelope env = new ReferencedEnvelope(w, e, s, n, CRS.decode("EPSG:4326"));

            ReferencedEnvelope wmsEnv = env.transform(CRS.decode(wmscode), false);
            BufferedImage image = ww.getImage(ww.getMapRequest(layer, null, wmscode, width, height, wmsEnv, null, null));
            String format = "jpg";
            if (outputImage.toLowerCase().endsWith("png")) {
                format = "png";
            }
            ImageIO.write(image, format, new File(outputImage));
            break;
        }
    }
}
 
Example 7
Source File: GeoServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void crsInfoTest() throws Exception {
	CoordinateReferenceSystem crs = CRS.decode(LONLAT);
	Assert.assertNotNull(crs);
	Assert.assertEquals(4326, geoService.getSridFromCrs(crs));
	Assert.assertEquals(LONLAT, geoService.getCodeFromCrs(crs));

	Assert.assertEquals(900913, geoService.getSridFromCrs(MERCATOR));
	Assert.assertEquals(4326, geoService.getSridFromCrs(LONLAT));
	Assert.assertEquals(123, geoService.getSridFromCrs("123"));
	Assert.assertEquals(0, geoService.getSridFromCrs("bla"));
}
 
Example 8
Source File: SpatialTemporalDimensionalityTypeProvider.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static CoordinateReferenceSystem decodeCRS(final String crsCode) {

    CoordinateReferenceSystem crs = null;
    try {
      crs = CRS.decode(crsCode, true);
    } catch (final FactoryException e) {
      LOGGER.error("Unable to decode '" + crsCode + "' CRS", e);
      throw new RuntimeException("Unable to decode '" + crsCode + "' CRS", e);
    }

    return crs;
  }
 
Example 9
Source File: GeoHashGridTest.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test(expected=IllegalArgumentException.class)
public void testGeoHashGridWithNoDocCount() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1))))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(i-> assertArrayEquals(new float[geohashGrid.getGrid()[i].length], geohashGrid.getGrid()[i], 0.0f));
}
 
Example 10
Source File: CoordinateUtils.java    From TomboloDigitalConnector with MIT License 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 11
Source File: FeatureDataAdapter.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static CoordinateReferenceSystem decodeCRS(final String crsCode) {

    CoordinateReferenceSystem crs = null;
    try {
      crs = CRS.decode(crsCode, true);
    } catch (final FactoryException e) {
      LOGGER.error("Unable to decode '" + crsCode + "' CRS", e);
      throw new RuntimeException("Unable to initialize '" + crsCode + "' object", e);
    }

    return crs;
  }
 
Example 12
Source File: GridCoverageWritable.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void readFields(final DataInput input) throws IOException {
  final int rasterTileSize = Varint.readUnsignedVarInt(input);
  final byte[] rasterTileBinary = new byte[rasterTileSize];
  input.readFully(rasterTileBinary);
  rasterTile = new RasterTile();
  rasterTile.fromBinary(rasterTileBinary);
  minX = input.readDouble();
  maxX = input.readDouble();
  minY = input.readDouble();
  maxY = input.readDouble();
  final int crsStrSize = Varint.readUnsignedVarInt(input);

  if (crsStrSize > 0) {
    final byte[] crsStrBytes = new byte[crsStrSize];
    input.readFully(crsStrBytes);
    final String crsStr = StringUtils.stringFromBinary(crsStrBytes);
    try {
      crs = CRS.decode(crsStr);
    } catch (final FactoryException e) {
      LOGGER.error("Unable to decode " + crsStr + " CRS", e);
      throw new RuntimeException("Unable to decode " + crsStr + " CRS", e);
    }
  } else {
    crs = GeometryUtils.getDefaultCRS();
  }
}
 
Example 13
Source File: GeoHashGridTest.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGeoHashGridWithNoFeatures() throws Exception {
    features = new DefaultFeatureCollection();
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(i-> assertArrayEquals(new float[geohashGrid.getGrid()[i].length], geohashGrid.getGrid()[i], 0.0f));
}
 
Example 14
Source File: GeoHashGridTest.java    From elasticgeo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testGeoHashGridWithProjectedEnvelope() 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(-19926188.85,19926188.85,-30240971.96,30240971.96, CRS.decode("EPSG:3857"));
    geohashGrid.initalize(envelope, features);

    assertEquals(new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84), geohashGrid.getBoundingBox());
}
 
Example 15
Source File: Wgs84Projection.java    From occurrence with Apache License 2.0 5 votes vote down vote up
/**
 * Parses the given datum or SRS code and constructs a full 2D geographic reference system.
 *
 * @return the parsed CRS or null if it can't be interpreted
 */
@VisibleForTesting
protected static CoordinateReferenceSystem parseCRS(String datum) {
  CoordinateReferenceSystem crs = null;
  ParseResult<Integer> epsgCode = PARSER.parse(datum);
  if (epsgCode.isSuccessful()) {
    final String code = "EPSG:" + epsgCode.getPayload();

    // first try to create a full fledged CRS from the given code
    try {
      crs = CRS.decode(code);

    } catch (FactoryException e) {
      // that didn't work, maybe it is *just* a datum
      try {
        GeodeticDatum dat = DATUM_FACTORY.createGeodeticDatum(code);
        crs = new DefaultGeographicCRS(dat, DefaultEllipsoidalCS.GEODETIC_2D);

      } catch (FactoryException e1) {
        // also not a datum, no further ideas, log error
        // swallow anything and return null instead
        LOG.info("No CRS or DATUM for given datum code >>{}<<: {}", datum, e1.getMessage());
      }
    }
  }
  return crs;
}
 
Example 16
Source File: CoordManagerTest.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Test method for {@link com.sldeditor.common.coordinate.CoordManager#getInstance()}. Test
 * method for {@link com.sldeditor.common.coordinate.CoordManager#getCRSList()}. Test method for
 * {@link
 * com.sldeditor.common.coordinate.CoordManager#getCRSCode(org.opengis.referencing.crs.CoordinateReferenceSystem)}.
 * Test method for {@link com.sldeditor.common.coordinate.CoordManager#getWGS84()}.
 *
 * @throws NoSuchAuthorityCodeException the no such authority code exception
 * @throws FactoryException the factory exception
 */
@Test
public void testGetInstance() throws NoSuchAuthorityCodeException, FactoryException {
    CoordManager.getInstance().populateCRSList();
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    List<ValueComboBoxData> crsList = CoordManager.getInstance().getCRSList();
    assertTrue(crsList.size() > 0);

    CoordinateReferenceSystem crs = CoordManager.getInstance().getCRS(null);
    assertNull(crs);

    crs = CoordManager.getInstance().getWGS84();
    assertTrue(crs != null);

    String code = CoordManager.getInstance().getCRSCode(null);
    assertTrue(code.compareTo("") == 0);

    code = CoordManager.getInstance().getCRSCode(crs);
    assertTrue(code.compareTo("EPSG:4326") == 0);

    String projectedCRSCode = "EPSG:27700";
    CoordinateReferenceSystem projectedCRS = CRS.decode(projectedCRSCode);

    code = CoordManager.getInstance().getCRSCode(projectedCRS);
    assertTrue(code.compareTo(projectedCRSCode) == 0);
}
 
Example 17
Source File: CoordManager.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets the coordinate reference object for the supplied CRS code.
 *
 * @param crsCode the crs code
 * @return the coordinate reference system
 */
public CoordinateReferenceSystem getCRS(String crsCode) {
    CoordinateReferenceSystem crs = null;

    if (crsCode != null) {
        try {
            crs = CRS.decode(crsCode);
        } catch (FactoryException e) {
            ConsoleManager.getInstance().exception(this, e);
        }
    }
    return crs;
}
 
Example 18
Source File: GeoServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void transformGeometryJtsCrs() throws Exception {
	Geometry geometry = getLineString();
	CoordinateReferenceSystem source = CRS.decode(LONLAT);
	CoordinateReferenceSystem target = CRS.decode(LAMBERT72);

	Assert.assertEquals(geometry, geoService.transform(geometry, source, source));

	geometry = geoService.transform(geometry, source, target);
	assertTransformedLineString(geometry);
}
 
Example 19
Source File: WebMapsController.java    From hortonmachine with GNU General Public License v3.0 4 votes vote down vote up
private CoordinateReferenceSystem getCrs( String epsg ) throws Exception {
    if (epsg.toUpperCase().equals("EPSG:4326")) {
        return DefaultGeographicCRS.WGS84;
    }
    return CRS.decode(epsg);
}
 
Example 20
Source File: GeotoolsDataStoreUtils.java    From TomboloDigitalConnector with MIT License 4 votes vote down vote up
public static MathTransform makeCrsTransform(String inputFormat) throws FactoryException {
    CoordinateReferenceSystem sourceCrs = CRS.decode(inputFormat);
    CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:"+Subject.SRID, true);

    return CRS.findMathTransform(sourceCrs, targetCrs);
}