Java org.opengis.referencing.crs.CoordinateReferenceSystem 代码实例

・17 分钟阅读

以下是展示如何使用org.opengis.referencing.crs.CoordinateReferenceSystem的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Returns a positive number if the specified coordinate system is right-handed,
 * or a negative number if it is left handed.
 */
private static double getAngle(final CoordinateReferenceSystem crs) {
    final CoordinateSystem cs = crs.getCoordinateSystem();
    assertEquals(2, cs.getDimension());
    return DefaultCoordinateSystemAxis.getAngle(cs.getAxis(0).getDirection(),
                                                cs.getAxis(1).getDirection());
}
 

实例 2


/**
 * Tests the (latitude, longitude) axis order for EPSG:4326.
 */
public void testCorrectAxisOrder() throws NoSuchAuthorityCodeException, FactoryException {
    final CoordinateReferenceSystem crs = CRS.decode("EPSG:4326");
    final CoordinateSystem cs = crs.getCoordinateSystem();
    assertEquals(2, cs.getDimension());
    CoordinateSystemAxis axis0 = cs.getAxis(0);
    assertEquals("Lat", axis0.getAbbreviation());
    CoordinateSystemAxis axis1 = cs.getAxis(1);
    assertEquals("Long", axis1.getAbbreviation());
}
 

实例 3


protected boolean areCRSEqual(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2) {
        if (crs1==null && crs2==null)
                return true;
        if (crs1==null ) return false;
        return crs1.equals(crs2); 
}
 

实例 4


/**
 * Constructor that will generate schema and mathTransform for the results.
 * 
 * @param reader original reader
 * @param cs Target coordinate reference system; will be used to create the target FeatureType and MathTransform used to transform the data
 */
public ReprojectFeatureReader(FeatureReader<SimpleFeatureType, SimpleFeature> reader,
    CoordinateReferenceSystem cs)
    throws SchemaException, OperationNotFoundException, NoSuchElementException, FactoryException{
    if (cs == null) {
        throw new NullPointerException("CoordinateSystem required");
    }
    SimpleFeatureType type = reader.getFeatureType();
    CoordinateReferenceSystem original = type.getGeometryDescriptor()
                                             .getCoordinateReferenceSystem();
    if (cs.equals(original)) {
        throw new IllegalArgumentException("CoordinateSystem " + cs
            + " already used (check before using wrapper)");
    }
    this.schema = FeatureTypes.transform(type, cs);
    this.reader = reader;
    transformer.setMathTransform(CRS.findMathTransform(original, cs, true));
}
 

实例 5


/**
 * Wraps feature collection as needed in order to respect the current projection policy and the
 * target CRS, if any (can be null, in that case only the projection policy is applied)
 */
protected SimpleFeatureCollection applyProjectionPolicies(
        CoordinateReferenceSystem targetCRS,
        SimpleFeatureCollection fc)
        throws IOException, SchemaException, TransformException,
        OperationNotFoundException, FactoryException {
    if ( fc.getSchema().getGeometryDescriptor() == null ) {
        // reprojection and crs forcing do not make sense, bail out
        return fc;
    } 
    CoordinateReferenceSystem nativeCRS = fc.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem();
    if(nativeCRS == null) {
        if(declaredCRS != null) {
            fc =  new ForceCoordinateSystemFeatureResults(fc, declaredCRS);
            nativeCRS = declaredCRS;
        }
    } else if(srsHandling == ProjectionPolicy.FORCE_DECLARED && !nativeCRS.equals(declaredCRS)) {
        fc =  new ForceCoordinateSystemFeatureResults(fc, declaredCRS);
        nativeCRS = declaredCRS;
    } else if(srsHandling == ProjectionPolicy.REPROJECT_TO_DECLARED && targetCRS == null
            && !nativeCRS.equals(declaredCRS)) {
        fc = new ReprojectFeatureResults(fc,declaredCRS);
    }
    //was reproject specified as part of the query?
    if (targetCRS != null ) {
        //reprojection is occuring
        if ( nativeCRS == null ) {
            //we do not know what the native crs which means we can 
            // not be sure if we should reproject or not... so we go 
            // ahead and reproject regardless
            fc = new ReprojectFeatureResults(fc,targetCRS);
        }
        else {
            //only reproject if native != target
            if (!CRS.equalsIgnoreMetadata(nativeCRS, targetCRS)) {
                fc = new ReprojectFeatureResults(fc,targetCRS);                        
            }
        }
    }
    return fc;
}
 

实例 6


protected boolean areCRSEqual(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2) {
        if (crs1==null && crs2==null)
                return true;
        if (crs1==null ) return false;
        return crs1.equals(crs2); 
}
 

实例 7


/**
 * Constructor that will generate schema and mathTransform for the results.
 * 
 * @param reader original reader
 * @param cs Target coordinate reference system; will be used to create the target FeatureType and MathTransform used to transform the data
 */
public ReprojectFeatureReader(FeatureReader<SimpleFeatureType, SimpleFeature> reader,
    CoordinateReferenceSystem cs)
    throws SchemaException, OperationNotFoundException, NoSuchElementException, FactoryException{
    if (cs == null) {
        throw new NullPointerException("CoordinateSystem required");
    }
    SimpleFeatureType type = reader.getFeatureType();
    CoordinateReferenceSystem original = type.getGeometryDescriptor()
                                             .getCoordinateReferenceSystem();
    if (cs.equals(original)) {
        throw new IllegalArgumentException("CoordinateSystem " + cs
            + " already used (check before using wrapper)");
    }
    this.schema = FeatureTypes.transform(type, cs);
    this.reader = reader;
    transformer.setMathTransform(CRS.findMathTransform(original, cs, true));
}
 

实例 8


/**
 * This method is used to force the creation of a .prj file.
 * <p>
 * The internally cached FeatureType will be removed, so the next call to
 * getSchema() will read in the created file. This method is not thread safe
 * and will have dire consequences for any other thread making use of the
 * shapefile.
 * <p>
 * 
 * @param crs
 */
public void forceSchemaCRS(CoordinateReferenceSystem crs)
        throws IOException {
    if (crs == null)
        throw new NullPointerException("CRS required for .prj file");
    String s = crs.toWKT();
    s = s.replaceAll("n", "").replaceAll("  ", "");
    StorageFile storageFile = shpFiles.getStorageFile(PRJ);
    FileWriter out = new FileWriter(storageFile.getFile());
    try {
        out.write(s);
    } finally {
        out.close();
    }
    storageFile.replaceOriginal();
    schema = null;
}
 

实例 9


/**
 * Tests parsing with custom axis length. At the difference of the previous test,
 * the WKT formatting in this test should include the axis length as parameter values.
 */
@Test
public void testCustomAxisLength() throws FactoryException, ParseException {
    DefaultMathTransformFactory factory = new DefaultMathTransformFactory();
    ParameterValueGroup parameters = factory.getDefaultParameters("Lambert_Conformal_Conic_2SP");
    final double majorAxis = 6.3712e+6;
    final double minorAxis = 6.3712e+6;
    parameters.parameter("semi_major").setValue(majorAxis);
    parameters.parameter("semi_minor").setValue(minorAxis);
    parameters.parameter("latitude_of_origin").setValue(25.0);
    parameters.parameter("standard_parallel_1").setValue(25.0);
    parameters.parameter("standard_parallel_2").setValue(25.0);
    parameters.parameter("longitude_of_origin").setValue(-95.0);
    parameters.parameter("false_easting").setValue(0.0);
    parameters.parameter("false_northing").setValue(0.0);
    GeographicCRS base = DefaultGeographicCRS.WGS84;
    MathTransform mt   = factory.createParameterizedTransform(parameters);
    CartesianCS cs = DefaultCartesianCS.PROJECTED;
    CoordinateReferenceSystem crs = new DefaultProjectedCRS("Lambert", base, mt, cs);
    final String wkt = crs.toWKT();
    assertTrue(wkt.contains("semi_major"));
    assertTrue(wkt.contains("semi_minor"));
    final Parser parser = new Parser();
    CoordinateReferenceSystem check = parser.parseCoordinateReferenceSystem(wkt);
    assertEquals(wkt, check.toWKT());
}
 

实例 10


/**
 * @param crs
 */
public static CRSWrapper fromCRS(CoordinateReferenceSystem crs) {
    CRSWrapper result = new CRSWrapper();
    result.wkt = crs.toWKT();
    result.type = "geographic";
    result.epsg = crs.getIdentifiers().iterator().next().toString();
    return result;
}
 

实例 11


private CrsGeoCoding createCRSGeoCoding(GeoCoding srcGeocoding) throws Exception {
    final CoordinateReferenceSystem srcCRS = srcGeocoding.getMapCRS();
    String wkt;
    try {
        wkt = srcCRS.toWKT();
    } catch (UnformattableObjectException e) {        // if too complex to convert using strict
        wkt = srcCRS.toString();
    }
    final CoordinateReferenceSystem targetCRS = CRSGeoCodingHandler.getCRS(wkt);
    final double pixelSpacingInDegree = pixelSize / Constants.semiMajorAxis * Constants.RTOD;
    double pixelSizeX = pixelSize;
    double pixelSizeY = pixelSize;
    if (targetCRS.getName().getCode().equals("WGS84(DD)")) {
        pixelSizeX = pixelSpacingInDegree;
        pixelSizeY = pixelSpacingInDegree;
    }
    final Rectangle2D bounds = new Rectangle2D.Double();
    bounds.setFrameFromDiagonal(scnProp.lonMin, scnProp.latMin, scnProp.lonMax, scnProp.latMax);
    final ReferencedEnvelope boundsEnvelope = new ReferencedEnvelope(bounds, DefaultGeographicCRS.WGS84);
    final ReferencedEnvelope targetEnvelope = boundsEnvelope.transform(targetCRS, true);
    return new CrsGeoCoding(targetCRS,
            sceneWidth,
            sceneHeight,
            targetEnvelope.getMinimum(0),
            targetEnvelope.getMaximum(1),
            pixelSizeX, pixelSizeY);
}
 

实例 12


@Override
public String toString(Object obj) {
    CoordinateReferenceSystem crs = (CoordinateReferenceSystem) obj;
    try {
        Integer epsg = CRS.lookupEpsgCode(crs, true);
        if (epsg != null) {
            return "EPSG:" + epsg;
        }
    } 
    catch (FactoryException e) {
        XStreamPersister.LOGGER.warning( "Could not determine epsg code of crs, encoding as WKT");
    }
    return crs.toWKT();
}
 

实例 13


/**
 * Performs the conversion, returns the name of the (main) output file 
 */
public File convert(File inputData, File outputDirectory, String typeName,
        OgrFormat format, CoordinateReferenceSystem crs) throws IOException, InterruptedException {
    // build the command line
    List<String> cmd = new ArrayList<String>();
    cmd.add(ogrExecutable);
    cmd.add("-f");
    cmd.add(format.ogrFormat);
    File crsFile = null;
    if (crs != null) {
        // we don't use an EPSG code since there is no guarantee we'll be able to reverse
        // engineer one. Using WKT also ensures the EPSG params such as the TOWGS84 ones are
        // not lost in the conversion
        // We also write to a file because some operating systems cannot take arguments with
        // quotes and spaces inside (and/or ProcessBuilder is not good enough to escape them)
        crsFile = File.createTempFile("gdal_srs", "wkt", inputData.getParentFile());
        cmd.add("-a_srs");
        String s = crs.toWKT();
        s = s.replaceAll("nr", "").replaceAll("  ", "");
        FileUtils.writeStringToFile(crsFile, s);
        cmd.add(crsFile.getAbsolutePath());
    }
    if (format.options != null) {
        for (String option : format.options) {
            cmd.add(option);
        }
    }
    String outFileName = typeName;
    if (format.fileExtension != null)
        outFileName += format.fileExtension;
    cmd.add(new File(outputDirectory, outFileName).getAbsolutePath());
    cmd.add(inputData.getAbsolutePath());
    StringBuilder sb = new StringBuilder();
    int exitCode = run(cmd, sb);
    if(crsFile != null) {
        crsFile.delete();
    }
    if (exitCode != 0)
        throw new IOException("ogr2ogr did not terminate successfully, exit code " + exitCode
                + ". Was trying to run: " + cmd + "nResulted in:n" + sb);
    // csv output is a directory, handle that case gracefully
    File output = new File(outputDirectory, outFileName);
    if(output.isDirectory()) {
        output = new File(output, outFileName);
    }
    return output;
}
 

实例 14


public void toWKT() throws Exception {
    // toWKT start
    CoordinateReferenceSystem crs = CRS.decode("EPSG:32735");
    String wkt = crs.toWKT();
    System.out.println("wkt for EPSG:32735");
    System.out.println( wkt );
    // toWKT end
}
 

实例 15


@Override
public CRSDefinition resolveCRS(final CoordinateReferenceSystem crs) {
        CRSDefinition result = cached.get(crs);
        if (result == null) {
                try {
                        Integer epsgCode = CRS.lookupEpsgCode(crs, true);
                        if (epsgCode != null) {
                                String code = SrsSyntax.OGC_URN + String.valueOf(epsgCode);
                                CoordinateReferenceSystem resolved = CRS.decode(code);
                                result = new CodeDefinition(code, resolved);
                        }
                } catch (FactoryException e) {
                        // ignore
                }
                if (result == null) {
                        // prevent further lookups of this CRS
                        result = new WKTDefinition(crs.toWKT(), crs);
                }
                cached.put(crs, result);
        }
        return result;
}
 
讨论
淘淘あ西西 profile image