Java Code Examples for org.opengis.referencing.crs.CoordinateReferenceSystem#getCoordinateSystem()

The following examples show how to use org.opengis.referencing.crs.CoordinateReferenceSystem#getCoordinateSystem() . 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: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * @param val the value
 * @param crs
 * @param axis the coordinate axis
 * @return
 */
private static double clipRange(
    final double val,
    final CoordinateReferenceSystem crs,
    final int axis) {
  final CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
  if (coordinateSystem.getDimension() > axis) {
    final CoordinateSystemAxis coordinateAxis = coordinateSystem.getAxis(axis);
    if (val < coordinateAxis.getMinimumValue()) {
      return coordinateAxis.getMinimumValue();
    } else if (val > coordinateAxis.getMaximumValue()) {
      return coordinateAxis.getMaximumValue();
    }
  }
  return val;
}
 
Example 2
Source File: GeometryUtils.java    From geowave with Apache License 2.0 6 votes vote down vote up
/**
 * This is perhaps a brain dead approach to do this, but it does handle wrap around cases. Also
 * supports cases where the wrap around occurs many times.
 *
 * @param val the value
 * @param crs
 * @param axis the coordinate axis
 * @return the adjusted coordinate dimension
 */
public static double adjustCoordinateDimensionToRange(
    final double val,
    final CoordinateReferenceSystem crs,
    final int axis) {
  final CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
  if (coordinateSystem.getDimension() > axis) {
    final double lowerBound = coordinateSystem.getAxis(axis).getMinimumValue();
    final double bound = coordinateSystem.getAxis(axis).getMaximumValue() - lowerBound;
    final double sign = sign(val);
    // re-scale to 0 to n, then determine how many times to 'loop
    // around'
    final double mult = Math.floor(Math.abs((val + (sign * (-1.0 * lowerBound))) / bound));
    return val + (mult * bound * sign * (-1.0));
  }
  return val;
}
 
Example 3
Source File: EllipsoidalHeightCombiner.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the coordinate system if the given CRS is a two-dimensional geographic or projected CRS,
 * or {@code null} otherwise. The returned coordinate system is either ellipsoidal or Cartesian;
 * no other type is returned.
 */
private static CoordinateSystem getCsIfHorizontal2D(final CoordinateReferenceSystem crs) {
    final boolean isProjected = (crs instanceof ProjectedCRS);
    if (isProjected || crs instanceof GeodeticCRS) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        if (cs.getDimension() == 2 && (isProjected || cs instanceof EllipsoidalCS)) {
            /*
             * ProjectedCRS are guaranteed to be associated to CartesianCS, so we do not test that.
             * GeodeticCRS may be associated to either CartesianCS or EllipsoidalCS, but this method
             * shall accept only EllipsoidalCS. Actually we should accept only GeographicCRS, but we
             * relax this condition by accepting GeodeticCRS with EllipsoidalCS.
             */
            return cs;
        }
    }
    return null;
}
 
Example 4
Source File: DefaultCompoundCRS.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a compound coordinate system for the specified array of CRS objects.
 *
 * @param  properties  the properties given to the constructor, or {@code null} if unknown.
 * @param  components  the CRS components, usually singles but not necessarily.
 * @return the coordinate system for the given components.
 */
private static CoordinateSystem createCoordinateSystem(final Map<String,?> properties,
        final CoordinateReferenceSystem[] components)
{
    ArgumentChecks.ensureNonNull("components", components);
    verify(properties, components);
    if (components.length < 2) {
        throw new IllegalArgumentException(Errors.getResources(properties).getString(
                Errors.Keys.TooFewArguments_2, 2, components.length));
    }
    final CoordinateSystem[] cs = new CoordinateSystem[components.length];
    for (int i=0; i<components.length; i++) {
        final CoordinateReferenceSystem crs = components[i];
        ArgumentChecks.ensureNonNullElement("components", i, crs);
        cs[i] = crs.getCoordinateSystem();
    }
    return new DefaultCompoundCS(cs);
}
 
Example 5
Source File: FeatureDataUtils.java    From geowave with Apache License 2.0 5 votes vote down vote up
public static String getAxis(final CoordinateReferenceSystem crs) {
  // Some geometries do not have a CRS provided. Thus we default to
  // urn:ogc:def:crs:EPSG::4326
  final CoordinateSystem cs = crs == null ? null : crs.getCoordinateSystem();
  if ((cs != null) && (cs.getDimension() > 0)) {
    return cs.getAxis(0).getDirection().name().toString();
  }
  return "EAST";
}
 
Example 6
Source File: ArgumentChecks.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the given CRS, if non-null, has the expected number of dimensions.
 * This method does nothing if the given coordinate reference system is null.
 *
 * @param  name      the name of the argument to be checked. Used only if an exception is thrown.
 * @param  expected  the expected number of dimensions.
 * @param  crs       the coordinate reference system to check for its dimension, or {@code null}.
 * @throws MismatchedDimensionException if the given coordinate reference system is non-null
 *         and does not have the expected number of dimensions.
 */
public static void ensureDimensionMatches(final String name, final int expected,
        final CoordinateReferenceSystem crs) throws MismatchedDimensionException
{
    if (crs != null) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        if (cs != null) {                                       // Should never be null, but let be safe.
            final int dimension = cs.getDimension();
            if (dimension != expected) {
                throw new MismatchedDimensionException(Errors.format(
                        Errors.Keys.MismatchedDimension_3, name, expected, dimension));
            }
        }
    }
}
 
Example 7
Source File: Angle.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the angular value of the axis having the given direction.
 * This helper method is used for subclass constructors expecting a {@link DirectPosition} argument.
 *
 * @param  position  the position from which to get an angular value.
 * @param  positive  axis direction of positive values.
 * @param  negative  axis direction of negative values.
 * @return angular value in degrees.
 * @throws IllegalArgumentException if the given coordinate it not associated to a CRS,
 *         or if no axis oriented toward the given directions is found, or if that axis
 *         does not use {@linkplain Units#isAngular angular units}.
 */
static double valueOf(final DirectPosition position, final AxisDirection positive, final AxisDirection negative) {
    final CoordinateReferenceSystem crs = position.getCoordinateReferenceSystem();
    if (crs == null) {
        throw new IllegalArgumentException(Errors.format(Errors.Keys.UnspecifiedCRS));
    }
    final CoordinateSystem cs = crs.getCoordinateSystem();
    final int dimension = cs.getDimension();
    IncommensurableException cause = null;
    for (int i=0; i<dimension; i++) {
        final CoordinateSystemAxis axis = cs.getAxis(i);
        final AxisDirection dir = axis.getDirection();
        final boolean isPositive = dir.equals(positive);
        if (isPositive || dir.equals(negative)) {
            double value = position.getOrdinate(i);
            if (!isPositive) value = -value;
            final Unit<?> unit = axis.getUnit();
            if (unit != Units.DEGREE) try {
                value = unit.getConverterToAny(Units.DEGREE).convert(value);
            } catch (IncommensurableException e) {
                cause = e;
                break;
            }
            return value;
        }
    }
    throw new IllegalArgumentException(Errors.format(Errors.Keys.IllegalCRSType_1,
            Classes.getLeafInterfaces(crs.getClass(), CoordinateReferenceSystem.class)[0]), cause);
}
 
Example 8
Source File: EPSGFactoryFallbackTest.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that the result of {@link EPSGFactoryFallback#createObject(String)} is CS of the given CRS.
 * Contrarily to other kinds of objects, coordinate systems are currently not cached. Consequently we
 * can not assert that instances are the same.
 */
private static void verifyCreateCS(final CoordinateReferenceSystem crs, final String code) throws FactoryException {
    final CoordinateSystem expected = crs.getCoordinateSystem();
    final CoordinateSystem actual = EPSGFactoryFallback.INSTANCE.createCoordinateSystem(code);
    assertEquals(code, actual, EPSGFactoryFallback.INSTANCE.createObject(code));
    assertEqualsIgnoreMetadata(expected, actual);
}
 
Example 9
Source File: WKTUtilities.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Suggests an amount of fraction digits to use for formatting numbers in each column of the given sequence
 * of points. The number of fraction digits may be negative if we could round the numbers to 10, <i>etc</i>.
 *
 * @param  crs     the coordinate reference system for each points, or {@code null} if unknown.
 * @param  points  the sequence of points. It is not required that each point has the same dimension.
 * @return suggested amount of fraction digits as an array as long as the longest row.
 */
public static int[] suggestFractionDigits(final CoordinateReferenceSystem crs, final Vector[] points) {
    final int[] fractionDigits = Numerics.suggestFractionDigits(points);
    final Ellipsoid ellipsoid = ReferencingUtilities.getEllipsoid(crs);
    if (ellipsoid != null) {
        /*
         * Use heuristic precisions for geodetic or projected CRS. We do not apply those heuristics
         * for other kind of CRS (e.g. engineering) because we do not know what could be the size
         * of the object attached to the CRS.
         */
        final CoordinateSystem cs = crs.getCoordinateSystem();
        final int dimension = Math.min(cs.getDimension(), fractionDigits.length);
        final double scale = Formulas.scaleComparedToEarth(ellipsoid);
        for (int i=0; i<dimension; i++) {
            final Unit<?> unit = cs.getAxis(i).getUnit();
            double precision;
            if (Units.isLinear(unit)) {
                precision = Formulas.LINEAR_TOLERANCE * scale;                          // In metres
            } else if (Units.isAngular(unit)) {
                precision = Formulas.ANGULAR_TOLERANCE * (Math.PI / 180) * scale;       // In radians
            } else if (Units.isTemporal(unit)) {
                precision = Formulas.TEMPORAL_TOLERANCE;                                // In seconds
            } else {
                continue;
            }
            precision /= Units.toStandardUnit(unit);                // In units used by the coordinates.
            final int f = DecimalFunctions.fractionDigitsForDelta(precision, false);
            if (f > fractionDigits[i]) {
                fractionDigits[i] = f;                              // Use at least the heuristic precision.
            }
        }
    }
    return fractionDigits;
}
 
Example 10
Source File: AbstractEnvelope.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the axis of the given coordinate reference system for the given dimension,
 * or {@code null} if none.
 *
 * @param  crs        the envelope CRS, or {@code null}.
 * @param  dimension  the dimension for which to get the axis.
 * @return the axis at the given dimension, or {@code null}.
 */
static CoordinateSystemAxis getAxis(final CoordinateReferenceSystem crs, final int dimension) {
    if (crs != null) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        if (cs != null) {                                       // Paranoiac check (should never be null).
            return cs.getAxis(dimension);
        }
    }
    return null;
}
 
Example 11
Source File: AbstractDirectPosition.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that the position is contained in the coordinate system domain.
 * For each dimension, this method compares the coordinate values against the
 * limits of the coordinate system axis for that dimension.
 * If some coordinates are out of range, then there is a choice depending on the
 * {@linkplain CoordinateSystemAxis#getRangeMeaning() axis range meaning}:
 *
 * <ul>
 *   <li>If {@link RangeMeaning#EXACT} (typically <em>latitudes</em> coordinates), then values
 *       greater than the {@linkplain CoordinateSystemAxis#getMaximumValue() axis maximal value}
 *       are replaced by the axis maximum, and values smaller than the
 *       {@linkplain CoordinateSystemAxis#getMinimumValue() axis minimal value}
 *       are replaced by the axis minimum.</li>
 *
 *   <li>If {@link RangeMeaning#WRAPAROUND} (typically <em>longitudes</em> coordinates), then
 *       a multiple of the axis range (e.g. 360° for longitudes) is added or subtracted.</li>
 * </ul>
 *
 * @return {@code true} if this position has been modified as a result of this method call,
 *         or {@code false} if no change has been done.
 *
 * @see GeneralEnvelope#normalize()
 */
public boolean normalize() {
    boolean changed = false;
    final CoordinateReferenceSystem crs = getCoordinateReferenceSystem();
    if (crs != null) {
        final int dimension = getDimension();
        final CoordinateSystem cs = crs.getCoordinateSystem();
        for (int i=0; i<dimension; i++) {
            double coordinate = getOrdinate(i);
            final CoordinateSystemAxis axis = cs.getAxis(i);
            final double  minimum = axis.getMinimumValue();
            final double  maximum = axis.getMaximumValue();
            final RangeMeaning rm = axis.getRangeMeaning();
            if (RangeMeaning.EXACT.equals(rm)) {
                     if (coordinate < minimum) coordinate = minimum;
                else if (coordinate > maximum) coordinate = maximum;
                else continue;
            } else if (RangeMeaning.WRAPAROUND.equals(rm)) {
                final double csSpan = maximum - minimum;
                final double shift  = Math.floor((coordinate - minimum) / csSpan) * csSpan;
                if (shift == 0) {
                    continue;
                }
                coordinate -= shift;
            }
            setOrdinate(i, coordinate);
            changed = true;
        }
    }
    return changed;
}
 
Example 12
Source File: CRS.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * If the given CRS would qualify as horizontal except for its number of dimensions, returns that number.
 * Otherwise returns 0. The number of dimensions can only be 2 or 3.
 */
private static int horizontalCode(final CoordinateReferenceSystem crs) {
    /*
     * In order to determine if the CRS is geographic, checking the CoordinateSystem type is more reliable
     * then checking if the CRS implements the GeographicCRS interface.  This is because the GeographicCRS
     * type did not existed in ISO 19111:2007, so a CRS could be standard-compliant without implementing
     * the GeographicCRS interface.
     */
    boolean isEngineering = false;
    final boolean isGeodetic = (crs instanceof GeodeticCRS);
    if (isGeodetic || crs instanceof ProjectedCRS || (isEngineering = (crs instanceof EngineeringCRS))) {
        final CoordinateSystem cs = crs.getCoordinateSystem();
        final int dim = cs.getDimension();
        if ((dim & ~1) == 2 && (!isGeodetic || (cs instanceof EllipsoidalCS))) {
            if (isEngineering) {
                int n = 0;
                for (int i=0; i<dim; i++) {
                    if (AxisDirections.isCompass(cs.getAxis(i).getDirection())) n++;
                }
                // If we don't have exactly 2 east, north, etc. directions, consider as non-horizontal.
                if (n != 2) return 0;
            }
            return dim;
        }
    }
    return 0;
}
 
Example 13
Source File: GeoWaveRasterReader.java    From geowave with Apache License 2.0 5 votes vote down vote up
private static int indexOf(
    final CoordinateReferenceSystem crs,
    final Set<AxisDirection> direction) {
  final CoordinateSystem cs = crs.getCoordinateSystem();
  for (int index = 0; index < cs.getDimension(); index++) {
    final CoordinateSystemAxis axis = cs.getAxis(index);
    if (direction.contains(axis.getDirection())) {
      return index;
    }
  }
  return -1;
}
 
Example 14
Source File: BoundsInputPanel.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
public void updatePixelUnit(CoordinateReferenceSystem crs) {
    final CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
    final String unitX = coordinateSystem.getAxis(0).getUnit().toString();
    if (!unitX.equals(pixelXUnit.getText())) {
        pixelXUnit.setText(unitX);
        pixelSizeXField.setValue(unitMap.get(unitX));
    }
    final String unitY = coordinateSystem.getAxis(1).getUnit().toString();
    if (!unitY.equals(pixelYUnit.getText())) {
        pixelYUnit.setText(unitY);
        pixelSizeYField.setValue(unitMap.get(unitY));
    }
}
 
Example 15
Source File: ServicesForMetadata.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Implementation of the public {@code setBounds(…, DefaultGeographicBoundingBox, …)} methods for
 * the horizontal extent. If the {@code crs} argument is null, then it is caller's responsibility
 * to ensure that the given envelope is two-dimensional.
 *
 * <p>If {@code findOpCaller} is non-null, then this method will be executed in optional mode:
 * some failures will cause this method to return {@code null} instead than throwing an exception.
 * Note that {@link TransformException} may still be thrown but not directly by this method.
 * Warning may be logged, but in such case this method presumes that public caller is the named
 * method from {@link Envelopes} — typically {@link Envelopes#findOperation(Envelope, Envelope)}.</p>
 *
 * @param  envelope       the source envelope.
 * @param  target         the target bounding box, or {@code null} for creating it automatically.
 * @param  crs            the envelope CRS, or {@code null} if unknown.
 * @param  normalizedCRS  the horizontal component of the given CRS, or null if the {@code crs} argument is null.
 * @param  findOpCaller   non-null for replacing some (not all) exceptions by {@code null} return value.
 * @return the bounding box or {@code null} on failure. Never {@code null} if {@code findOpCaller} argument is {@code null}.
 * @throws TransformException if the given envelope can not be transformed.
 */
private static DefaultGeographicBoundingBox setGeographicExtent(Envelope envelope, DefaultGeographicBoundingBox target,
        final CoordinateReferenceSystem crs, final GeographicCRS normalizedCRS, final String findOpCaller) throws TransformException
{
    if (normalizedCRS != null) {
        // No need to check for dimension, since GeodeticCRS can not have less than 2.
        final CoordinateSystem cs1 = crs.getCoordinateSystem();
        final CoordinateSystem cs2 = normalizedCRS.getCoordinateSystem();
        if (!Utilities.equalsIgnoreMetadata(cs2.getAxis(0), cs1.getAxis(0)) ||
            !Utilities.equalsIgnoreMetadata(cs2.getAxis(1), cs1.getAxis(1)))
        {
            final CoordinateOperation operation;
            final CoordinateOperationFactory factory = CoordinateOperations.factory();
            try {
                operation = factory.createOperation(crs, normalizedCRS);
            } catch (FactoryException e) {
                if (findOpCaller != null) {
                    // See javadoc for the assumption that optional mode is used by Envelopes.findOperation(…).
                    Logging.recoverableException(Logging.getLogger(Modules.REFERENCING), Envelopes.class, findOpCaller, e);
                    return null;
                }
                throw new TransformException(Resources.format(Resources.Keys.CanNotTransformEnvelopeToGeodetic), e);
            }
            envelope = Envelopes.transform(operation, envelope);
        }
    }
    /*
     * At this point, the envelope should use (longitude, latitude) coordinates in degrees.
     * The envelope may cross the anti-meridian if the envelope implementation is an Apache SIS one.
     * For other implementations, the longitude range may be conservatively expanded to [-180 … 180]°.
     */
    double westBoundLongitude, eastBoundLongitude;
    double southBoundLatitude, northBoundLatitude;
    if (envelope instanceof AbstractEnvelope) {
        final AbstractEnvelope ae = (AbstractEnvelope) envelope;
        westBoundLongitude = ae.getLower(0);
        eastBoundLongitude = ae.getUpper(0);            // Cross anti-meridian if eastBoundLongitude < westBoundLongitude.
        southBoundLatitude = ae.getLower(1);
        northBoundLatitude = ae.getUpper(1);
    } else {
        westBoundLongitude = envelope.getMinimum(0);
        eastBoundLongitude = envelope.getMaximum(0);    // Expanded to [-180 … 180]° if it was crossing the anti-meridian.
        southBoundLatitude = envelope.getMinimum(1);
        northBoundLatitude = envelope.getMaximum(1);
    }
    /*
     * The envelope transformation at the beginning of this method intentionally avoided to apply datum shift.
     * This implies that the prime meridian has not been changed and may be something else than Greenwich.
     * We need to take it in account manually.
     *
     * Note that there is no need to normalize the longitudes back to the [-180 … +180]° range after the rotation, or
     * to verify if the longitude span is 360°. Those verifications will be done automatically by target.setBounds(…).
     */
    if (normalizedCRS != null) {
        final double rotation = CRS.getGreenwichLongitude(normalizedCRS);
        westBoundLongitude += rotation;
        eastBoundLongitude += rotation;
    }
    /*
     * In the particular case where this method is invoked (indirectly) for Envelopes.findOperation(…) purposes,
     * replace NaN values by the whole world.  We do that only for Envelopes.findOperation(…) since we know that
     * the geographic bounding box will be used for choosing a CRS, and a conservative approach is to select the
     * CRS valid in the widest area. If this method is invoked for other usages, then we keep NaN values because
     * we don't know the context (union, intersection, something else?).
     */
    if (findOpCaller != null) {
        if (Double.isNaN(southBoundLatitude)) southBoundLatitude = Latitude.MIN_VALUE;
        if (Double.isNaN(northBoundLatitude)) northBoundLatitude = Latitude.MAX_VALUE;
        if (Double.isNaN(eastBoundLongitude) || Double.isNaN(westBoundLongitude)) {
            // Conservatively set the two bounds because may be spanning the anti-meridian.
            eastBoundLongitude = Longitude.MIN_VALUE;
            westBoundLongitude = Longitude.MAX_VALUE;
        }
    }
    if (target == null) {
        target = new DefaultGeographicBoundingBox();
    }
    target.setBounds(westBoundLongitude, eastBoundLongitude, southBoundLatitude, northBoundLatitude);
    target.setInclusion(Boolean.TRUE);
    return target;
}
 
Example 16
Source File: SubTypes.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a SIS implementation for the given coordinate reference system.
 *
 * @see AbstractCRS#castOrCopy(CoordinateReferenceSystem)
 */
static AbstractCRS castOrCopy(final CoordinateReferenceSystem object) {
    if (object instanceof DerivedCRS) {
        return DefaultDerivedCRS.castOrCopy((DerivedCRS) object);
    }
    if (object instanceof ProjectedCRS) {
        return DefaultProjectedCRS.castOrCopy((ProjectedCRS) object);
    }
    if (object instanceof GeodeticCRS) {
        if (object instanceof GeographicCRS) {
            return DefaultGeographicCRS.castOrCopy((GeographicCRS) object);
        }
        if (object instanceof GeocentricCRS) {
            return DefaultGeocentricCRS.castOrCopy((GeocentricCRS) object);
        }
        /*
         * The GeographicCRS and GeocentricCRS types are not part of ISO 19111.
         * ISO uses a single type, GeodeticCRS, for both of them and infer the
         * geographic or geocentric type from the coordinate system. We do this
         * check here for instantiating the most appropriate SIS type, but only
         * if we need to create a new object anyway (see below for rational).
         */
        if (object instanceof DefaultGeodeticCRS) {
            /*
             * Result of XML unmarshalling — keep as-is. We avoid creating a new object because it
             * would break object identities specified in GML document by the xlink:href attribute.
             * However we may revisit this policy in the future. See SC_CRS.setElement(AbstractCRS).
             */
            return (DefaultGeodeticCRS) object;
        }
        final Map<String,?> properties = IdentifiedObjects.getProperties(object);
        final GeodeticDatum datum = ((GeodeticCRS) object).getDatum();
        final CoordinateSystem cs = object.getCoordinateSystem();
        if (cs instanceof EllipsoidalCS) {
            return new DefaultGeographicCRS(properties, datum, (EllipsoidalCS) cs);
        }
        if (cs instanceof SphericalCS) {
            return new DefaultGeocentricCRS(properties, datum, (SphericalCS) cs);
        }
        if (cs instanceof CartesianCS) {
            return new DefaultGeocentricCRS(properties, datum, (CartesianCS) cs);
        }
    }
    if (object instanceof VerticalCRS) {
        return DefaultVerticalCRS.castOrCopy((VerticalCRS) object);
    }
    if (object instanceof TemporalCRS) {
        return DefaultTemporalCRS.castOrCopy((TemporalCRS) object);
    }
    if (object instanceof EngineeringCRS) {
        return DefaultEngineeringCRS.castOrCopy((EngineeringCRS) object);
    }
    if (object instanceof ImageCRS) {
        return DefaultImageCRS.castOrCopy((ImageCRS) object);
    }
    if (object instanceof CompoundCRS) {
        return DefaultCompoundCRS.castOrCopy((CompoundCRS) object);
    }
    /*
     * Intentionally check for AbstractCRS after the interfaces because user may have defined his own
     * subclass implementing the interface. If we were checking for AbstractCRS before the interfaces,
     * the returned instance could have been a user subclass without the JAXB annotations required
     * for XML marshalling.
     */
    if (object == null || object instanceof AbstractCRS) {
        return (AbstractCRS) object;
    }
    return new AbstractCRS(object);
}
 
Example 17
Source File: MetadataBuilder.java    From sis with Apache License 2.0 4 votes vote down vote up
/**
 * Adds and populates a "spatial representation info" node using the given grid geometry.
 * This method invokes implicitly {@link #newGridRepresentation(GridType)}, unless this
 * method returns {@code false} in which case nothing has been done.
 * Storage location is:
 *
 * <ul>
 *   <li>{@code metadata/spatialRepresentationInfo/transformationDimensionDescription}</li>
 *   <li>{@code metadata/spatialRepresentationInfo/transformationParameterAvailability}</li>
 *   <li>{@code metadata/spatialRepresentationInfo/axisDimensionProperties/dimensionName}</li>
 *   <li>{@code metadata/spatialRepresentationInfo/axisDimensionProperties/dimensionSize}</li>
 *   <li>{@code metadata/spatialRepresentationInfo/axisDimensionProperties/resolution}</li>
 *   <li>{@code metadata/identificationInfo/spatialRepresentationType}</li>
 *   <li>{@code metadata/referenceSystemInfo}</li>
 * </ul>
 *
 * This method does not add the envelope provided by {@link GridGeometry#getEnvelope()}.
 * That envelope appears in a separated node, which can be added by {@link #addExtent(Envelope)}.
 * This separation is required by {@link AbstractGridResource} for instance.
 *
 * @param  description    a general description of the "grid to CRS" transformation, or {@code null} if none.
 *                        Can also be specified later by a call to {@link #setGridToCRS(CharSequence)}.
 * @param  grid           the grid extent, "grid to CRS" transform and target CRS, or {@code null} if none.
 * @param  addResolution  whether to declare the resolutions. Callers should set this argument to {@code false} if they intend
 *                        to provide the resolution themselves, or if grid axes are not in the same order than CRS axes.
 * @return whether a "spatial representation info" node has been added.
 */
public final boolean addSpatialRepresentation(final String description, final GridGeometry grid, final boolean addResolution) {
    final GridType type;
    if (grid == null) {
        if (description == null) {
            return false;
        }
        type = GridType.UNSPECIFIED;
    } else {
        type = grid.isConversionLinear(0, 1) ? GridType.GEORECTIFIED : GridType.GEOREFERENCEABLE;
    }
    addSpatialRepresentation(SpatialRepresentationType.GRID);
    newGridRepresentation(type);
    setGridToCRS(description);
    if (grid != null) {
        setGeoreferencingAvailability(grid.isDefined(GridGeometry.GRID_TO_CRS), false, false);
        CoordinateSystem cs = null;
        if (grid.isDefined(GridGeometry.CRS)) {
            final CoordinateReferenceSystem crs = grid.getCoordinateReferenceSystem();
            cs = crs.getCoordinateSystem();
            addReferenceSystem(crs);
        }
        if (grid.isDefined(GridGeometry.EXTENT)) {
            final GridExtent extent = grid.getExtent();
            final int dimension = extent.getDimension();
            for (int i=0; i<dimension; i++) {
                final Optional<DimensionNameType> axisType = extent.getAxisType(i);
                if (axisType.isPresent()) {
                    setAxisName(i, axisType.get());
                }
                setAxisSize(i, extent.getSize(i));
            }
        }
        if (addResolution && grid.isDefined(GridGeometry.RESOLUTION)) {
            final double[] resolution = grid.getResolution(false);
            for (int i=0; i<resolution.length; i++) {
                setAxisResolution(i, resolution[i], (cs != null) ? cs.getAxis(i).getUnit() : null);
            }
        }
    }
    return true;
}
 
Example 18
Source File: AbstractCRS.java    From sis with Apache License 2.0 2 votes vote down vote up
/**
 * Constructs a new coordinate reference system with the same values than the specified one.
 * This copy constructor provides a way to convert an arbitrary implementation into a SIS one
 * or a user-defined one (as a subclass), usually in order to leverage some implementation-specific API.
 *
 * <p>This constructor performs a shallow copy, i.e. the properties are not cloned.</p>
 *
 * @param  crs  the coordinate reference system to copy.
 *
 * @see #castOrCopy(CoordinateReferenceSystem)
 */
protected AbstractCRS(final CoordinateReferenceSystem crs) {
    super(crs);
    coordinateSystem = crs.getCoordinateSystem();
}