Search in sources :

Example 1 with MathTransform

use of org.opengis.referencing.operation.MathTransform in project spatial-portal by AtlasOfLivingAustralia.

the class Util method createCircle.

public static String createCircle(double x, double y, final double radius, int sides) {
    try {
        GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
        String wkt4326 = "GEOGCS[" + "\"WGS 84\"," + "  DATUM[" + "    \"WGS_1984\"," + "    SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]]," + "    TOWGS84[0,0,0,0,0,0,0]," + "    AUTHORITY[\"EPSG\",\"6326\"]]," + "  PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]]," + "  UNIT[\"DMSH\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9108\"]]," + "  AXIS[\"Lat\",NORTH]," + "  AXIS[\"Long\",EAST]," + "  AUTHORITY[\"EPSG\",\"4326\"]]";
        String wkt900913 = "PROJCS[\"WGS84 / Google Mercator\", " + "  GEOGCS[\"WGS 84\", " + "   DATUM[\"World Geodetic System 1984\", " + "   SPHEROID[\"WGS 84\", 6378137.0, 298.257223563, AUTHORITY[\"EPSG\",\"7030\"]], " + "  AUTHORITY[\"EPSG\",\"6326\"]], " + " PRIMEM[\"Greenwich\", 0.0, AUTHORITY[\"EPSG\",\"8901\"]], " + " UNIT[\"degree\", 0.017453292519943295], " + " AXIS[\"Longitude\", EAST], " + " AXIS[\"Latitude\", NORTH], " + " AUTHORITY[\"EPSG\",\"4326\"]], " + " PROJECTION[\"Mercator_1SP\"], " + " PARAMETER[\"semi_minor\", 6378137.0], " + " PARAMETER[\"latitude_of_origin\", 0.0]," + " PARAMETER[\"central_meridian\", 0.0], " + " PARAMETER[\"scale_factor\", 1.0], " + " PARAMETER[\"false_easting\", 0.0], " + " PARAMETER[\"false_northing\", 0.0], " + " UNIT[\"m\", 1.0], " + " AXIS[\"x\", EAST], " + " AXIS[\"y\", NORTH], " + " AUTHORITY[\"EPSG\",\"3857\"]] ";
        CoordinateReferenceSystem wgsCRS = CRS.parseWKT(wkt4326);
        CoordinateReferenceSystem googleCRS = CRS.parseWKT(wkt900913);
        MathTransform transform = CRS.findMathTransform(wgsCRS, googleCRS);
        Point point = geometryFactory.createPoint(new Coordinate(y, x));
        Geometry geom = JTS.transform(point, transform);
        Point gPoint = geometryFactory.createPoint(new Coordinate(geom.getCoordinate()));
        LOGGER.debug("Google point:" + gPoint.getCoordinate().x + "," + gPoint.getCoordinate().y);
        MathTransform reverseTransform = CRS.findMathTransform(googleCRS, wgsCRS);
        Coordinate[] coords = new Coordinate[sides + 1];
        for (int i = 0; i < sides; i++) {
            double angle = ((double) i / (double) sides) * Math.PI * 2.0;
            double dx = Math.cos(angle) * radius;
            double dy = Math.sin(angle) * radius;
            geom = JTS.transform(geometryFactory.createPoint(new Coordinate(gPoint.getCoordinate().x + dx, gPoint.getCoordinate().y + dy)), reverseTransform);
            coords[i] = new Coordinate(geom.getCoordinate().y, geom.getCoordinate().x);
        }
        coords[sides] = coords[0];
        LinearRing ring = geometryFactory.createLinearRing(coords);
        Polygon polygon = geometryFactory.createPolygon(ring, null);
        WKTWriter writer = new WKTWriter();
        String wkt = writer.write(polygon);
        return wkt.replaceAll(StringConstants.POLYGON + " ", StringConstants.POLYGON).replaceAll(", ", ",");
    } catch (Exception e) {
        LOGGER.debug("Circle fail!");
        return StringConstants.NONE;
    }
}
Also used : WKTWriter(com.vividsolutions.jts.io.WKTWriter) MathTransform(org.opengis.referencing.operation.MathTransform) ParseException(com.vividsolutions.jts.io.ParseException) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 2 with MathTransform

use of org.opengis.referencing.operation.MathTransform in project spatial-portal by AtlasOfLivingAustralia.

the class AreaUploadShapefileWizardController method loadOnMap.

private void loadOnMap(Set<FeatureId> ids, String filename) {
    try {
        final FilterFactory ff = CommonFactoryFinder.getFilterFactory(GeoTools.getDefaultHints());
        Filter filter = ff.id(ids);
        // set up the math transform used to process the data
        SimpleFeatureType schema = features.getSchema();
        CoordinateReferenceSystem dataCRS = schema.getCoordinateReferenceSystem();
        CoordinateReferenceSystem wgsCRS = DefaultGeographicCRS.WGS84;
        // allow for some error due to different datums
        boolean lenient = true;
        if (dataCRS == null) {
            //attempt to parse prj
            try {
                File prjFile = new File(filename.substring(0, filename.length() - 3) + "prj");
                if (prjFile.exists()) {
                    String prj = FileUtils.readFileToString(prjFile);
                    if (prj.equals("PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0]]")) {
                        //support for arcgis online default shp exports
                        dataCRS = CRS.decode("EPSG:3857");
                    } else {
                        dataCRS = CRS.parseWKT(FileUtils.readFileToString(prjFile));
                    }
                }
            } catch (Exception e) {
                LOGGER.error("failed to read prj for " + filename);
            }
            if (dataCRS == null) {
                dataCRS = DefaultGeographicCRS.WGS84;
            }
        }
        MathTransform transform = CRS.findMathTransform(dataCRS, wgsCRS, lenient);
        SimpleFeatureCollection sff = source.getFeatures(filter);
        SimpleFeatureIterator fif = sff.features();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        List<Geometry> geoms = new ArrayList<Geometry>();
        while (fif.hasNext()) {
            SimpleFeature f = fif.next();
            LOGGER.debug("Selected Feature: " + f.getID() + " -> " + f.getAttribute("ECOREGION"));
            Geometry geom = (Geometry) f.getDefaultGeometry();
            geom = JTS.transform(geom, transform);
            String wktString = geom.toText();
            wktString = wktString.replaceAll(", ", ",");
            boolean valid = true;
            boolean multipolygon = false;
            boolean polygon = false;
            boolean geometrycollection = false;
            if (wktString.startsWith(StringConstants.MULTIPOLYGON + " ")) {
                wktString = wktString.substring((StringConstants.MULTIPOLYGON + " ").length(), wktString.length() - 1);
                multipolygon = true;
            } else if (wktString.startsWith(StringConstants.POLYGON + " ")) {
                wktString = wktString.substring((StringConstants.POLYGON + " ").length());
                polygon = true;
            } else if (wktString.startsWith(StringConstants.GEOMETRYCOLLECTION + " (")) {
                wktString = wktString.substring((StringConstants.GEOMETRYCOLLECTION + " (").length(), wktString.length() - 1);
                geometrycollection = true;
                isGeometryCollection = true;
            } else {
                valid = false;
            }
            if (valid) {
                if (sb.length() > 0) {
                    sb.append(",");
                    sbGeometryCollection.append(",");
                }
                sb.append(wktString);
                if (multipolygon) {
                    sbGeometryCollection.append(StringConstants.MULTIPOLYGON).append("(").append(wktString.replace("(((", "(("));
                    if (!wktString.endsWith(")))")) {
                        sbGeometryCollection.append(")");
                    }
                } else if (polygon) {
                    sbGeometryCollection.append(StringConstants.POLYGON).append(wktString);
                } else if (geometrycollection) {
                    sbGeometryCollection.append(wktString);
                }
            }
        }
        String wkt;
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            wkt = StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "((");
        } else {
            sbGeometryCollection.append(")");
            wkt = StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection.toString();
            getMapComposer().showMessage("Shape is invalid: " + "GEOMETRYCOLLECTION not supported.");
        }
        GeometryFactory gf = new GeometryFactory();
        gf.createGeometryCollection(GeometryFactory.toGeometryArray(geoms));
        String msg = "";
        boolean invalid = false;
        try {
            WKTReader wktReader = new WKTReader();
            com.vividsolutions.jts.geom.Geometry g = wktReader.read(wkt);
            //NC 20130319: Ensure that the WKT is valid according to the WKT standards.
            IsValidOp op = new IsValidOp(g);
            if (!op.isValid()) {
                //this will fix some issues
                g = g.buffer(0);
                op = new IsValidOp(g);
            }
            if (!op.isValid()) {
                invalid = true;
                LOGGER.warn(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + op.getValidationError().getMessage());
                msg = op.getValidationError().getMessage();
            //TODO Fix invalid WKT text using https://github.com/tudelft-gist/prepair maybe???
            } else if (g.isRectangle()) {
                //NC 20130319: When the shape is a rectangle ensure that the points a specified in the correct order.
                //get the new WKT for the rectangle will possibly need to change the order.
                com.vividsolutions.jts.geom.Envelope envelope = g.getEnvelopeInternal();
                String wkt2 = StringConstants.POLYGON + "((" + envelope.getMinX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMinY() + "," + envelope.getMaxX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMaxY() + "," + envelope.getMinX() + " " + envelope.getMinY() + "))";
                if (!wkt.equals(wkt2)) {
                    LOGGER.debug("NEW WKT for Rectangle: " + wkt);
                    msg = CommonData.lang("error_wkt_anticlockwise");
                    invalid = true;
                }
            }
            if (!invalid) {
                invalid = !op.isValid();
            }
        } catch (ParseException parseException) {
            LOGGER.error("error testing validity of uploaded shape file wkt", parseException);
        }
        if (invalid) {
            getMapComposer().showMessage(CommonData.lang(StringConstants.ERROR_WKT_INVALID) + " " + msg);
        } else {
            MapLayer mapLayer = getMapComposer().addWKTLayer(wkt, layername, layername);
            UserDataDTO ud = new UserDataDTO(layername);
            ud.setFilename(media.getName());
            ud.setUploadedTimeInMs(System.currentTimeMillis());
            ud.setType("shapefile");
            String metadata = "";
            metadata += "User uploaded Shapefile \n";
            metadata += "Name: " + ud.getName() + " <br />\n";
            metadata += "Filename: " + ud.getFilename() + " <br />\n";
            metadata += "Date: " + ud.getDisplayTime() + " <br />\n";
            metadata += "Selected polygons (fid): <br />\n";
            metadata += "<ul>";
            metadata += "</ul>";
            mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
            getMapComposer().replaceWKTwithWMS(mapLayer);
        }
    } catch (IOException e) {
        LOGGER.debug("IO Error retrieving geometry", e);
    } catch (Exception e) {
        LOGGER.debug("Generic Error retrieving geometry", e);
    }
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) MathTransform(org.opengis.referencing.operation.MathTransform) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) ReferencedEnvelope(org.geotools.geometry.jts.ReferencedEnvelope) FilterFactory(org.opengis.filter.FilterFactory) SimpleFeatureIterator(org.geotools.data.simple.SimpleFeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem) IOException(java.io.IOException) ParseException(com.vividsolutions.jts.io.ParseException) IOException(java.io.IOException) SimpleFeature(org.opengis.feature.simple.SimpleFeature) SimpleFeatureCollection(org.geotools.data.simple.SimpleFeatureCollection) Geometry(com.vividsolutions.jts.geom.Geometry) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) Filter(org.opengis.filter.Filter) IsValidOp(com.vividsolutions.jts.operation.valid.IsValidOp) ParseException(com.vividsolutions.jts.io.ParseException) File(java.io.File)

Example 3 with MathTransform

use of org.opengis.referencing.operation.MathTransform in project ddf by codice.

the class GeospatialUtil method transformToEPSG4326LonLatFormat.

/**
     * Transform a geometry to EPSG:4326 format with lon/lat coordinate ordering.
     * NOTE: This method will NOT perform the transform swapping coordinates even if the sourceCrsName is
     * EPSG:4326.
     *
     * @param geometry  - Geometry to transform
     * @param sourceCrs - Source geometry's coordinate reference system
     * @return Geometry - Transformed geometry into EPSG:4326 lon/lat coordinate system
     */
public static Geometry transformToEPSG4326LonLatFormat(Geometry geometry, CoordinateReferenceSystem sourceCrs) throws GeoFormatException {
    if (geometry == null) {
        throw new GeoFormatException("Unable to convert null geometry");
    }
    //If we don't have source CRS just return geometry as we can't transform without that information
    if (sourceCrs == null || CollectionUtils.isEmpty(sourceCrs.getIdentifiers())) {
        return geometry;
    }
    Geometry transformedGeometry = geometry;
    try {
        boolean sourceCrsMatchesTarget = false;
        for (ReferenceIdentifier referenceIdentifier : sourceCrs.getIdentifiers()) {
            if (referenceIdentifier.toString().equalsIgnoreCase(EPSG_4326)) {
                sourceCrsMatchesTarget = true;
                break;
            }
        }
        if (!sourceCrsMatchesTarget) {
            Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
            CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
            CoordinateReferenceSystem targetCRS = factory.createCoordinateReferenceSystem(EPSG_4326);
            MathTransform transform = CRS.findMathTransform(sourceCrs, targetCRS);
            transformedGeometry = JTS.transform(geometry, transform);
            LOGGER.debug("Converted CRS {} into {} : {}", sourceCrs, EPSG_4326, geometry);
        }
    } catch (FactoryException | TransformException e) {
        throw new GeoFormatException("Unable to convert coordinate to " + EPSG_4326, e);
    }
    return transformedGeometry;
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) ReferenceIdentifier(org.opengis.referencing.ReferenceIdentifier) Hints(org.geotools.factory.Hints) MathTransform(org.opengis.referencing.operation.MathTransform) FactoryException(org.opengis.referencing.FactoryException) GeoFormatException(org.codice.ddf.libs.geo.GeoFormatException) TransformException(org.opengis.referencing.operation.TransformException) CRSAuthorityFactory(org.opengis.referencing.crs.CRSAuthorityFactory) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Example 4 with MathTransform

use of org.opengis.referencing.operation.MathTransform in project ddf by codice.

the class GeospatialUtil method transformToEPSG4326LonLatFormat.

/**
     * Transform a geometry to EPSG:4326 format with lon/lat coordinate ordering.
     * NOTE: This method will perform the transform swapping coordinates even if the sourceCrsName is
     * EPSG:4326
     *
     * @param geometry      - Geometry to transform
     * @param sourceCrsName - Source geometry's coordinate reference system
     * @return Geometry - Transformed geometry into EPSG:4326 lon/lat coordinate system
     */
public static Geometry transformToEPSG4326LonLatFormat(Geometry geometry, String sourceCrsName) throws GeoFormatException {
    if (geometry == null) {
        throw new GeoFormatException("Unable to convert null geometry");
    }
    //If we don't have source CRS just return geometry as we can't transform without that information
    if (sourceCrsName == null) {
        return geometry;
    }
    try {
        CoordinateReferenceSystem sourceCrs = CRS.decode(sourceCrsName);
        Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
        CRSAuthorityFactory factory = ReferencingFactoryFinder.getCRSAuthorityFactory("EPSG", hints);
        CoordinateReferenceSystem targetCRS = factory.createCoordinateReferenceSystem(EPSG_4326);
        MathTransform transform = CRS.findMathTransform(sourceCrs, targetCRS);
        return JTS.transform(geometry, transform);
    } catch (FactoryException | TransformException e) {
        throw new GeoFormatException("Unable to convert coordinate to " + EPSG_4326, e);
    }
}
Also used : Hints(org.geotools.factory.Hints) MathTransform(org.opengis.referencing.operation.MathTransform) FactoryException(org.opengis.referencing.FactoryException) GeoFormatException(org.codice.ddf.libs.geo.GeoFormatException) TransformException(org.opengis.referencing.operation.TransformException) CRSAuthorityFactory(org.opengis.referencing.crs.CRSAuthorityFactory) CoordinateReferenceSystem(org.opengis.referencing.crs.CoordinateReferenceSystem)

Aggregations

CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)4 MathTransform (org.opengis.referencing.operation.MathTransform)4 Geometry (com.vividsolutions.jts.geom.Geometry)2 ParseException (com.vividsolutions.jts.io.ParseException)2 GeoFormatException (org.codice.ddf.libs.geo.GeoFormatException)2 Hints (org.geotools.factory.Hints)2 FactoryException (org.opengis.referencing.FactoryException)2 CRSAuthorityFactory (org.opengis.referencing.crs.CRSAuthorityFactory)2 TransformException (org.opengis.referencing.operation.TransformException)2 UserDataDTO (au.org.ala.spatial.dto.UserDataDTO)1 MapLayer (au.org.emii.portal.menu.MapLayer)1 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)1 WKTReader (com.vividsolutions.jts.io.WKTReader)1 WKTWriter (com.vividsolutions.jts.io.WKTWriter)1 IsValidOp (com.vividsolutions.jts.operation.valid.IsValidOp)1 File (java.io.File)1 IOException (java.io.IOException)1 SimpleFeatureCollection (org.geotools.data.simple.SimpleFeatureCollection)1 SimpleFeatureIterator (org.geotools.data.simple.SimpleFeatureIterator)1 ReferencedEnvelope (org.geotools.geometry.jts.ReferencedEnvelope)1