Search in sources :

Example 6 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project spatial-portal by AtlasOfLivingAustralia.

the class ShapefileUtils method saveShapefile.

public static void saveShapefile(File shpfile, String wktString, String name) {
    try {
        final SimpleFeatureType type = createFeatureType();
        List<SimpleFeature> features = new ArrayList<SimpleFeature>();
        SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(type);
        WKTReader wkt = new WKTReader();
        Geometry geom = wkt.read(wktString);
        if (geom instanceof GeometryCollection) {
            GeometryCollection gc = (GeometryCollection) geom;
            for (int i = 0; i < gc.getNumGeometries(); i++) {
                Geometry g = gc.getGeometryN(i);
                if (g instanceof Polygon) {
                    g = new GeometryBuilder().multiPolygon((Polygon) g);
                }
                featureBuilder.add(g);
                SimpleFeature feature = featureBuilder.buildFeature(null);
                feature.setAttribute("name", name);
                features.add(feature);
            }
        } else {
            Geometry g = geom;
            if (g instanceof Polygon) {
                g = new GeometryBuilder().multiPolygon((Polygon) g);
            }
            featureBuilder.add(g);
            SimpleFeature feature = featureBuilder.buildFeature(null);
            features.add(feature);
        }
        ShapefileDataStoreFactory dataStoreFactory = new ShapefileDataStoreFactory();
        Map<String, Serializable> params = new HashMap<String, Serializable>();
        params.put("url", shpfile.toURI().toURL());
        params.put("create spatial index", Boolean.TRUE);
        ShapefileDataStore newDataStore = (ShapefileDataStore) dataStoreFactory.createNewDataStore(params);
        newDataStore.createSchema(type);
        newDataStore.forceSchemaCRS(DefaultGeographicCRS.WGS84);
        Transaction transaction = new DefaultTransaction("create");
        String typeName = newDataStore.getTypeNames()[0];
        SimpleFeatureSource featureSource = newDataStore.getFeatureSource(typeName);
        if (featureSource instanceof SimpleFeatureStore) {
            SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
            DefaultFeatureCollection collection = new DefaultFeatureCollection();
            collection.addAll(features);
            featureStore.setTransaction(transaction);
            try {
                featureStore.addFeatures(collection);
                transaction.commit();
            } catch (Exception problem) {
                LOGGER.error("error pricessing shape file: " + shpfile.getAbsolutePath(), problem);
                transaction.rollback();
            } finally {
                transaction.close();
            }
        }
        LOGGER.debug("Active Area shapefile written to: " + shpfile.getAbsolutePath());
    } catch (Exception e) {
        LOGGER.error("Unable to save shapefile: " + shpfile.getAbsolutePath(), e);
    }
}
Also used : Serializable(java.io.Serializable) ShapefileDataStore(org.geotools.data.shapefile.ShapefileDataStore) HashMap(java.util.HashMap) SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) ArrayList(java.util.ArrayList) WKTReader(com.vividsolutions.jts.io.WKTReader) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) GeometryCollection(com.vividsolutions.jts.geom.GeometryCollection) SimpleFeatureType(org.opengis.feature.simple.SimpleFeatureType) SimpleFeatureStore(org.geotools.data.simple.SimpleFeatureStore) ShapefileDataStoreFactory(org.geotools.data.shapefile.ShapefileDataStoreFactory) MultiPolygon(com.vividsolutions.jts.geom.MultiPolygon) Polygon(com.vividsolutions.jts.geom.Polygon) GeometryBuilder(org.geotools.geometry.jts.GeometryBuilder) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) SimpleFeatureBuilder(org.geotools.feature.simple.SimpleFeatureBuilder)

Example 7 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project spatial-portal by AtlasOfLivingAustralia.

the class ShapefileUtils method loadShapefile.

public static Map loadShapefile(File shpfile) {
    try {
        FileDataStore store = FileDataStoreFinder.getDataStore(shpfile);
        LOGGER.debug("Loading shapefile. Reading content:");
        LOGGER.debug(store.getTypeNames()[0]);
        FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
        FeatureCollection featureCollection = featureSource.getFeatures();
        FeatureIterator it = featureCollection.features();
        Map shape = new HashMap();
        StringBuilder sb = new StringBuilder();
        StringBuilder sbGeometryCollection = new StringBuilder();
        boolean isGeometryCollection = false;
        while (it.hasNext()) {
            SimpleFeature feature = (SimpleFeature) it.next();
            Geometry geom = (Geometry) feature.getDefaultGeometry();
            WKTWriter wkt = new WKTWriter();
            String wktString = wkt.write(geom);
            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);
                }
            }
        }
        if (!isGeometryCollection) {
            if (!sb.toString().contains(")))")) {
                sb.append(")");
            }
            shape.put(StringConstants.WKT, StringConstants.MULTIPOLYGON + "(" + sb.toString().replace("(((", "(("));
        } else {
            sbGeometryCollection.append(")");
            shape.put(StringConstants.WKT, StringConstants.GEOMETRYCOLLECTION + "(" + sbGeometryCollection);
        }
        try {
            it.close();
        } catch (Exception e) {
        }
        return shape;
    } catch (Exception e) {
        LOGGER.error("Unable to load shapefile: ", e);
    }
    return null;
}
Also used : SimpleFeatureSource(org.geotools.data.simple.SimpleFeatureSource) WKTWriter(com.vividsolutions.jts.io.WKTWriter) HashMap(java.util.HashMap) SimpleFeature(org.opengis.feature.simple.SimpleFeature) FeatureIterator(org.geotools.feature.FeatureIterator) Geometry(com.vividsolutions.jts.geom.Geometry) DefaultFeatureCollection(org.geotools.feature.DefaultFeatureCollection) FeatureCollection(org.geotools.feature.FeatureCollection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 8 with Geometry

use of com.vividsolutions.jts.geom.Geometry 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 9 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project spatial-portal by AtlasOfLivingAustralia.

the class AooEooComposer method onFinish.

@Override
public boolean onFinish() {
    SelectedArea sa = getSelectedArea();
    Query q = getSelectedSpecies();
    q = q.newFacet(new Facet("occurrence_status_s", "absent", false), false);
    Facet f = new Facet("occurrence_status_s", "absent", false);
    q = q.newFacet(f, false);
    Query newQ = QueryUtil.queryFromSelectedArea(q, sa, false, null);
    double gridSize = dResolution.doubleValue();
    // eoo, use actual points
    LegendObject legend = newQ.getLegend("lat_long");
    StringBuilder sb = new StringBuilder();
    int pointCount = processLegend(legend, sb);
    String aooWkt = aooWkt(legend, gridSize);
    // aoo = gridSize * gridSize * number of gridSize by gridSize cells with an occurrence * (approx sq degrees to sq km)
    double aoo = gridSize * gridSize * aooProcess(legend, gridSize) * 10000;
    double eoo = 0;
    WKTReader reader = new WKTReader();
    String metadata = null;
    try {
        Geometry g = reader.read(sb.toString());
        Geometry convexHull = g.convexHull();
        String wkt = convexHull.toText().replace(" (", "(").replace(", ", ",");
        eoo = SpatialUtil.calculateArea(wkt);
        //aoo area
        Geometry a = reader.read(aooWkt(legend, gridSize));
        Geometry aUnion = a.union();
        String aWkt = aUnion.toText().replace(" (", "(").replace(", ", ",");
        if (eoo > 0) {
            String name = "Extent of occurrence (area): " + q.getName();
            MapLayer ml = getMapComposer().addWKTLayer(wkt, name, name);
            name = "Area of occupancy (area): " + q.getName();
            MapLayer mla = getMapComposer().addWKTLayer(aWkt, name, name);
            metadata = "<html><body>" + "<div class='aooeoo'>" + "<div>The Sensitive Data Service may have changed the location of taxa that have a sensitive status." + " It is wise to first map the taxa and examine each record, then filter these records to create the " + "desired subset, then run the tool on the new filtered taxa layer.</div><br />" + "<table >" + "<tr><td>Number of records used for the calculations</td><td>" + newQ.getOccurrenceCount() + "</td></tr>" + "<tr><td>Species</td><td>" + q.getName() + "</td></tr>" + "<tr><td>Area of Occupancy (AOO: " + gridSize + " degree grid)</td><td>" + String.format("%.0f", aoo) + " sq km</td></tr>" + "<tr><td>Extent of Occurrence (EOO: Minimum convex hull)</td><td>" + (String.format("%.2f", eoo / 1000.0 / 1000.0)) + " sq km</td></tr></table></body></html>" + "</div>";
            ml.getMapLayerMetadata().setMoreInfo("Area of Occupancy and Extent of Occurrence\n" + metadata);
            name = "Extent of occurrence (points): " + q.getName();
            MapLayer ml2 = getMapComposer().mapSpecies(newQ, name, StringConstants.SPECIES, newQ.getOccurrenceCount(), LayerUtilitiesImpl.SPECIES, null, 0, MapComposer.DEFAULT_POINT_SIZE, MapComposer.DEFAULT_POINT_OPACITY, Util.nextColour(), false);
            ml2.getMapLayerMetadata().setMoreInfo("Area of Occupancy and Extent of Occurrence\n" + metadata);
        } else {
            //trigger eoo unavailable message
            pointCount = 2;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    //show results
    String message = "The Sensitive Data Service may have changed the location of taxa that have a sensitive status. " + "It is wise to first map the taxa and examine each record, then filter these records to create the " + "desired subset, then run the tool on the new filtered taxa layer.\r\n" + "\r\nNumber of records used for the calculations: " + newQ.getOccurrenceCount() + "\r\nSpecies: " + q.getName() + "\r\nArea of Occupancy: " + String.format("%.0f", aoo) + " sq km" + "\r\nExtent of Occurrence: " + (pointCount < 3 ? "insufficient unique occurrence locations" : (String.format("%.2f", eoo / 1000.0 / 1000.0) + " sq km"));
    if (metadata != null) {
        Event ev = new Event(StringConstants.ONCLICK, null, "Area of Occupancy and Extent of Occurrence\n" + metadata);
        getMapComposer().openHTML(ev);
    } else {
        getMapComposer().showMessage(message);
    }
    //download metadata as text
    Filedownload.save(message, "text/plain", "Calculated AOO and EOO.txt");
    this.detach();
    return true;
}
Also used : Query(au.org.ala.spatial.util.Query) SelectedArea(au.org.emii.portal.menu.SelectedArea) MapLayer(au.org.emii.portal.menu.MapLayer) WKTReader(com.vividsolutions.jts.io.WKTReader) Geometry(com.vividsolutions.jts.geom.Geometry) LegendObject(au.org.ala.legend.LegendObject) Event(org.zkoss.zk.ui.event.Event) Facet(au.org.ala.legend.Facet)

Example 10 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project ignite by apache.

the class GridH2SpatialIndex method getEnvelope.

/**
     * @param row Row.
     * @param rowId Row id.
     * @return Envelope.
     */
private SpatialKey getEnvelope(SearchRow row, long rowId) {
    Value v = row.getValue(columnIds[0]);
    Geometry g = ((ValueGeometry) v.convertTo(Value.GEOMETRY)).getGeometry();
    Envelope env = g.getEnvelopeInternal();
    return new SpatialKey(rowId, (float) env.getMinX(), (float) env.getMaxX(), (float) env.getMinY(), (float) env.getMaxY());
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) ValueGeometry(org.h2.value.ValueGeometry) SpatialKey(org.h2.mvstore.rtree.SpatialKey) ValueGeometry(org.h2.value.ValueGeometry) Value(org.h2.value.Value) Envelope(com.vividsolutions.jts.geom.Envelope)

Aggregations

Geometry (com.vividsolutions.jts.geom.Geometry)123 WKTReader (com.vividsolutions.jts.io.WKTReader)35 Test (org.junit.Test)31 Coordinate (com.vividsolutions.jts.geom.Coordinate)23 Point (com.vividsolutions.jts.geom.Point)21 ParseException (com.vividsolutions.jts.io.ParseException)19 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)14 Envelope (com.vividsolutions.jts.geom.Envelope)13 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)13 WKTWriter (com.vividsolutions.jts.io.WKTWriter)13 ArrayList (java.util.ArrayList)12 LineString (com.vividsolutions.jts.geom.LineString)10 MultiPoint (com.vividsolutions.jts.geom.MultiPoint)9 Metacard (ddf.catalog.data.Metacard)9 SimpleFeature (org.opengis.feature.simple.SimpleFeature)7 Optional (com.google.common.base.Optional)6 IOException (java.io.IOException)6 RevFeature (org.locationtech.geogig.api.RevFeature)6 JtsGeometry (org.locationtech.spatial4j.shape.jts.JtsGeometry)6 GeometryCollection (com.vividsolutions.jts.geom.GeometryCollection)5