org.geotools.referencing.CRS Java Examples

The following examples show how to use org.geotools.referencing.CRS. 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: GeoTools.java    From xyz-hub with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a mathematical transformation from the first given EPSG coordinate reference system into the second one. This method can be
 * used in conjunction with the {@link JTS#transform(Geometry, MathTransform)} method.
 *
 * @param fromCrsId the CRS identifier of the source coordinate reference system.
 * @param toCrsId the CRS identifier of the destination coordinate reference system.
 * @throws NullPointerException if any of the given EPSG identifier is null.
 * @throws NoSuchAuthorityCodeException if any of the given EPSG identifier is unknown.
 * @throws FactoryException if the requested coordinate reference system can't be created or the transformation or the coordinate failed.
 */
public static MathTransform mathTransform(final String fromCrsId, final String toCrsId)
    throws NullPointerException, NoSuchAuthorityCodeException, FactoryException {
  if (fromCrsId == null) {
    throw new NullPointerException("fromCrsId");
  }
  if (toCrsId == null) {
    throw new NullPointerException("toCrsId");
  }
  final String id = fromCrsId + ":" + toCrsId;
  if (transformCache.containsKey(id)) {
    return transformCache.get(id);
  }
  final CoordinateReferenceSystem fromCRS = crs(fromCrsId);
  final CoordinateReferenceSystem toCRS = crs(toCrsId);
  final MathTransform newTransform = CRS.findMathTransform(fromCRS, toCRS, true);
  final MathTransform existingTransform = transformCache.putIfAbsent(id, newTransform);
  if (existingTransform != null) {
    return existingTransform;
  }
  return newTransform;
}
 
Example #3
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 #4
Source File: MBTilesHelper.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read the image of a tile from a generic geotools coverage reader.
 * 
 * @param reader the reader, expected to be in CRS 3857.
 * @param x the tile x.
 * @param y the tile y.
 * @param zoom the zoomlevel.
 * @return the image.
 * @throws IOException 
 */
public static BufferedImage readGridcoverageImageForTile( AbstractGridCoverage2DReader reader, int x, int y, int zoom,
        CoordinateReferenceSystem resampleCrs ) throws IOException {
    double north = tile2lat(y, zoom);
    double south = tile2lat(y + 1, zoom);
    double west = tile2lon(x, zoom);
    double east = tile2lon(x + 1, zoom);

    Coordinate ll = new Coordinate(west, south);
    Coordinate ur = new Coordinate(east, north);

    try {
        CoordinateReferenceSystem sourceCRS = DefaultGeographicCRS.WGS84;

        MathTransform transform = CRS.findMathTransform(sourceCRS, resampleCrs);
        ll = JTS.transform(ll, null, transform);
        ur = JTS.transform(ur, null, transform);
    } catch (Exception e) {
        e.printStackTrace();
    }

    BufferedImage image = ImageUtilities.imageFromReader(reader, TILESIZE, TILESIZE, ll.x, ur.x, ll.y, ur.y, resampleCrs);
    return image;
}
 
Example #5
Source File: GamaShapeFile.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public ShapeInfo(final String propertiesString) {
	super(propertiesString);
	final String[] segments = split(propertiesString);
	itemNumber = Integer.parseInt(segments[1]);
	final String crsString = segments[2];
	CoordinateReferenceSystem theCRS;
	if ("null".equals(crsString) || crsString.startsWith("Unknown")) {
		theCRS = null;
	} else {
		try {
			theCRS = CRS.parseWKT(crsString);
		} catch (final Exception e) {
			theCRS = null;
		}
	}
	crs = theCRS;
	width = Double.parseDouble(segments[3]);
	height = Double.parseDouble(segments[4]);
	if (segments.length > 5) {
		final String[] names = splitByWholeSeparatorPreserveAllTokens(segments[5], SUB_DELIMITER);
		final String[] types = splitByWholeSeparatorPreserveAllTokens(segments[6], SUB_DELIMITER);
		for (int i = 0; i < names.length; i++) {
			attributes.put(names[i], types[i]);
		}
	}
}
 
Example #6
Source File: SwtMapPane.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
public void setCrs(final CoordinateReferenceSystem crs) {
	try {
		final ReferencedEnvelope rEnv = getDisplayArea();

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

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

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

	} catch (final Exception e) {
		e.printStackTrace();
	}
}
 
Example #7
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 #8
Source File: FunctionAsWKT.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
@Override
public Object execute(Object argument, QLTerm qlterm)
		throws SAXException, IOException, ParserConfigurationException, FactoryException,
		MalformedGeometryException, ParseException {
	if (qlterm.equals(QLTerm.ROW_CLASS)){
		Object geom = argument;
		if (geom instanceof  String) {
			return "<http://www.opengis.net/def/crs/EPSG/0/" + Config.EPSG_CODE + "> " + geom;
		}
		else if (geom instanceof  Geometry){
			WKTWriter wkt = new WKTWriter();
			return "<http://www.opengis.net/def/crs/EPSG/0/" + Config.EPSG_CODE + "> " +  (wkt.write((Geometry) geom));
		}
	}
	else if (qlterm.equals(QLTerm.SHP_CLASS) && argument instanceof org.gdal.ogr.Geometry) {
		org.gdal.ogr.Geometry gdalgeom=(org.gdal.ogr.Geometry )argument;

		return "<http://www.opengis.net/def/crs/EPSG/0/" + Config.EPSG_CODE + "> " + gdalgeom.ExportToWkt();
	}

	Geometry geometry = computeGeometry(argument, qlterm);
	return GTransormationFunctions.asWKT((Geometry) geometry, CRS.decode("EPSG:" + Config.EPSG_CODE));
}
 
Example #9
Source File: SchemaConverter.java    From geowave with Apache License 2.0 6 votes vote down vote up
public static SimpleFeatureType schemaToFeatureType(
    final StructType schema,
    final String typeName) {
  final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  typeBuilder.setName(typeName);
  typeBuilder.setNamespaceURI(BasicFeatureTypes.DEFAULT_NAMESPACE);
  try {
    typeBuilder.setCRS(CRS.decode("EPSG:4326", true));
  } catch (final FactoryException e) {
    LOGGER.error(e.getMessage(), e);
  }

  final AttributeTypeBuilder attrBuilder = new AttributeTypeBuilder();

  for (final StructField field : schema.fields()) {
    final AttributeDescriptor attrDesc = attrDescFromStructField(attrBuilder, field);

    typeBuilder.add(attrDesc);
  }

  return typeBuilder.buildFeatureType();
}
 
Example #10
Source File: RasterizedSpatialiteLasLayer.java    From hortonmachine with GNU General Public License v3.0 6 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 #11
Source File: WKTConversion.java    From sldeditor with GNU General Public License v3.0 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 #12
Source File: DBScanIT.java    From geowave with Apache License 2.0 6 votes vote down vote up
private SimpleFeatureBuilder getBuilder() {
  final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  typeBuilder.setName("test");
  typeBuilder.setSRS(ClusteringUtils.CLUSTERING_CRS);
  try {
    typeBuilder.setCRS(CRS.decode(ClusteringUtils.CLUSTERING_CRS, true));
  } catch (final FactoryException e) {
    e.printStackTrace();
    return null;
  }
  // add attributes in order
  typeBuilder.add("geom", Point.class);
  typeBuilder.add("name", String.class);
  typeBuilder.add("count", Long.class);

  // build the type
  return new SimpleFeatureBuilder(typeBuilder.buildFeatureType());
}
 
Example #13
Source File: RL2NwwLayer.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public RL2NwwLayer( Rasterlite2Coverage rasterCoverage, Integer tileSize ) throws Exception {
    super(makeLevels(rasterCoverage, tileSize));
    this.layerName = rasterCoverage.getName();

    Envelope bounds = rasterCoverage.getBounds();
    double w = bounds.getMinX();
    double s = bounds.getMinY();
    double e = bounds.getMaxX();
    double n = bounds.getMaxY();

    double centerX = w + (e - w) / 2.0;
    double centerY = s + (n - s) / 2.0;
    Coordinate centerCoordinate = new Coordinate(centerX, centerY);

    CoordinateReferenceSystem targetCRS = DefaultGeographicCRS.WGS84;
    CoordinateReferenceSystem sourceCRS = CrsUtilities.getCrsFromSrid(rasterCoverage.getSrid());

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

    this.setUseTransparentTextures(true);

}
 
Example #14
Source File: GeometryDataSetGenerator.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static SimpleFeatureBuilder getBuilder(final String name) throws FactoryException {
  final SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
  typeBuilder.setName(name);
  typeBuilder.setCRS(CRS.decode("EPSG:4326", true)); // <- Coordinate
  // reference
  // add attributes in order
  typeBuilder.add("geom", Geometry.class);
  typeBuilder.add("name", String.class);
  typeBuilder.add("count", Long.class);

  // build the type
  return new SimpleFeatureBuilder(typeBuilder.buildFeatureType());
}
 
Example #15
Source File: AnalyticFeature.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static FeatureDataAdapter createFeatureAdapter(
    final String centroidDataTypeId,
    final String[] extraNumericDimensions,
    final String namespaceURI,
    final String SRID,
    final ClusterFeatureAttribute[] attributes,
    final Class<? extends Geometry> geometryClass) {
  try {
    final SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
    builder.setName(centroidDataTypeId);
    builder.setNamespaceURI(
        namespaceURI == null ? BasicFeatureTypes.DEFAULT_NAMESPACE : namespaceURI);
    builder.setSRS(SRID);
    builder.setCRS(CRS.decode(SRID, true));

    for (final ClusterFeatureAttribute attrVal : attributes) {
      builder.add(
          attrVal.name,
          attrVal.equals(ClusterFeatureAttribute.GEOMETRY) ? geometryClass : attrVal.type);
    }
    for (final String extraDim : extraNumericDimensions) {
      builder.add(extraDim, Double.class);
    }
    final FeatureDataAdapter adapter = new FeatureDataAdapter(builder.buildFeatureType());
    // TODO any consumers of this method will not be able to utilize
    // custom CRS
    adapter.init(new SpatialDimensionalityTypeProvider().createIndex(new SpatialOptions()));
    return adapter;
  } catch (final Exception e) {
    LOGGER.warn("Schema Creation Error.  Hint: Check the SRID.", e);
  }

  return null;
}
 
Example #16
Source File: GridCoverageWritable.java    From geowave with Apache License 2.0 5 votes vote down vote up
@Override
public void write(final DataOutput output) throws IOException {
  final byte[] rasterTileBinary = rasterTile.toBinary();
  Varint.writeUnsignedVarInt(rasterTileBinary.length, output);
  output.write(rasterTileBinary);
  output.writeDouble(minX);
  output.writeDouble(maxX);
  output.writeDouble(minY);
  output.writeDouble(maxY);
  final String crsStr =
      (crs == null) || GeometryUtils.getDefaultCRS().equals(crs) ? "" : CRS.toSRS(crs);
  Varint.writeUnsignedVarInt(crsStr.length(), output);
  output.write(StringUtils.stringToBinary(crsStr));
}
 
Example #17
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 #18
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CrsTransform getCrsTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	String key = getTransformKey(sourceCrs, targetCrs);
	CrsTransform transform = transformCache.get(key);
	if (null == transform) {
		MathTransform mathTransform = getBaseMathTransform(sourceCrs, targetCrs);

		// as there was no transformable area configured, try to build it instead
		Envelope transformableArea = null;
		try {
			org.opengis.geometry.Envelope ogEnvelope = CRS.getEnvelope(targetCrs);
			if (null != ogEnvelope) {
				Envelope envelope = new Envelope(ogEnvelope.getLowerCorner().getCoordinate()[0], ogEnvelope
						.getUpperCorner().getCoordinate()[0], ogEnvelope.getLowerCorner().getCoordinate()[1],
						ogEnvelope.getUpperCorner().getCoordinate()[1]);
				log.debug("CRS " + targetCrs.getId() + " envelope " + envelope);
				ReferencedEnvelope refEnvelope = new ReferencedEnvelope(envelope, targetCrs);
				transformableArea = refEnvelope.transform(sourceCrs, true);
				log.debug("transformable area for " + key + " is " + transformableArea);
			}
		} catch (MismatchedDimensionException mde) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					mde.getMessage()});
		} catch (TransformException te) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					te.getMessage()});
		} catch (FactoryException fe) {
			log.warn(WARN_TRANSFORMABLE_AREA, new Object[] {sourceCrs.getId(), targetCrs.getId(),
					fe.getMessage()});
		}

		transform = new CrsTransformImpl(key, sourceCrs, targetCrs, mathTransform, transformableArea);
		transformCache.put(key, transform);
	}
	return transform;
}
 
Example #19
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
private MathTransform getBaseMathTransform(Crs sourceCrs, Crs targetCrs) throws GeomajasException {
	try {
		MathTransform transform;
		try {
			transform = CRS.findMathTransform(sourceCrs, targetCrs);
		} catch (Exception e) { // NOSONAR GeoTools can throw unexpected exceptions
			transform = CRS.findMathTransform(sourceCrs, targetCrs, true);
		}
		return transform;
	} catch (FactoryException fe) {
		throw new GeomajasException(fe, ExceptionCode.CRS_TRANSFORMATION_NOT_POSSIBLE, sourceCrs.getId(),
				targetCrs.getId());
	}
}
 
Example #20
Source File: ProductLayerAssistantPage.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void collectCompatibleRasterDataNodes(CoordinateReferenceSystem thisCrs,
                                              RasterDataNode[] bands, Collection<RasterDataNode> rasterDataNodes) {
    for (RasterDataNode node : bands) {
        CoordinateReferenceSystem otherCrs = Product.findModelCRS(node.getGeoCoding());
        // For GeoTools, two CRS where unequal if the authorities of their CS only differ in version
        // This happened with the S-2 L1C CRS, namely an EPSG:32615. Here one authority's version was null,
        // the other "7.9". Extremely annoying to debug and find out :-(   (nf, Feb 2013)
        if (CRS.equalsIgnoreMetadata(thisCrs, otherCrs)
                || haveCommonReferenceIdentifiers(thisCrs, otherCrs)) {
            rasterDataNodes.add(node);
        }
    }
}
 
Example #21
Source File: NwwUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public static Sector envelope2Sector( ReferencedEnvelope env ) throws Exception {
    CoordinateReferenceSystem sourceCRS = env.getCoordinateReferenceSystem();
    CoordinateReferenceSystem targetCRS = GPS_CRS;

    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
    Envelope envLL = JTS.transform(env, transform);
    ReferencedEnvelope llEnv = new ReferencedEnvelope(envLL, targetCRS);
    Sector sector = Sector.fromDegrees(llEnv.getMinY(), llEnv.getMaxY(), llEnv.getMinX(), llEnv.getMaxX());
    return sector;
}
 
Example #22
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 #23
Source File: OverlayWorldMapLayerAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private boolean isGeographicLatLon(GeoCoding geoCoding) {
    if (geoCoding instanceof MapGeoCoding) {
        MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding;
        MapTransformDescriptor transformDescriptor = mapGeoCoding.getMapInfo()
                .getMapProjection().getMapTransform().getDescriptor();
        String typeID = transformDescriptor.getTypeID();
        if (typeID.equals(IdentityTransformDescriptor.TYPE_ID)) {
            return true;
        }
    } else if (geoCoding instanceof CrsGeoCoding) {
        return CRS.equalsIgnoreMetadata(geoCoding.getMapCRS(), DefaultGeographicCRS.WGS84);
    }
    return false;
}
 
Example #24
Source File: ExportGeometryAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private static GeometryCoordinateSequenceTransformer createTransformer(CoordinateReferenceSystem crs, CoordinateReferenceSystem modelCrs) {
    GeometryCoordinateSequenceTransformer transformer = new GeometryCoordinateSequenceTransformer();
    try {
        MathTransform reprojTransform = CRS.findMathTransform(crs, modelCrs, true);
        transformer.setMathTransform(reprojTransform);
        return transformer;
    } catch (FactoryException e) {
        throw new IllegalStateException("Could not create math transform", e);
    }
}
 
Example #25
Source File: GeoServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 #26
Source File: ShowGeometryWktAction.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private Geometry transformGeometry(Geometry sourceGeom,
                                   CoordinateReferenceSystem sourceCrs,
                                   CoordinateReferenceSystem targetCrs) throws FactoryException, TransformException {
    MathTransform mt = CRS.findMathTransform(sourceCrs, targetCrs, true);
    GeometryCoordinateSequenceTransformer gcst = new GeometryCoordinateSequenceTransformer();
    gcst.setMathTransform(mt);
    return gcst.transform(sourceGeom);
}
 
Example #27
Source File: ExportTimeBasedKmz.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    view = SnapApp.getDefault().getSelectedProductSceneView();
    final GeoCoding geoCoding = view.getProduct().getGeoCoding();
    boolean isGeographic = false;
    if (geoCoding instanceof MapGeoCoding) {
        MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding;
        MapTransformDescriptor transformDescriptor = mapGeoCoding.getMapInfo()
                .getMapProjection().getMapTransform().getDescriptor();
        String typeID = transformDescriptor.getTypeID();
        if (typeID.equals(IdentityTransformDescriptor.TYPE_ID)) {
            isGeographic = true;
        }
    } else if (geoCoding instanceof CrsGeoCoding) {
        isGeographic = CRS.equalsIgnoreMetadata(geoCoding.getMapCRS(), DefaultGeographicCRS.WGS84);
    }

    if (isGeographic) {
        final File output = fetchOutputFile(view);
        if (output == null) {
            return;
        }
        final String title = "KMZ Export";
        final ProgressMonitorSwingWorker worker = new KmzSwingWorker(title, output);
        worker.executeWithBlocking();
    } else {
        String message = "Product must be in ''Geographic Lat/Lon'' projection.";
        SnapDialogs.showInformation(message, null);
    }
}
 
Example #28
Source File: GeometryUtility.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Project geometry.
 *
 * @param originalGeom
 *            the original geom
 * @param srcCRSCode
 *            the src crs code
 * @param trgCRSCode
 *            the trg crs code
 * @return the geometry
 * @throws NoSuchAuthorityCodeException
 *             the no such authority code exception
 * @throws FactoryException
 *             the factory exception
 * @throws MismatchedDimensionException
 *             the mismatched dimension exception
 * @throws TransformException
 *             the transform exception
 */
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode,
    String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException,
    TransformException
{

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

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

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

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

    return projectedGeometry;
}
 
Example #29
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 #30
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"));
}