Search in sources :

Example 66 with Geometry

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

the class AreaMerge method mergeAreas.

void mergeAreas() {
    List<Facet> facets = new ArrayList<Facet>();
    List<Geometry> wkt = new ArrayList<Geometry>();
    WKTReader wktReader = new WKTReader();
    String layerDisplayNames = "";
    for (int i = 0; i < vboxAreas.getChildren().size(); i++) {
        Checkbox cb = (Checkbox) vboxAreas.getChildren().get(i);
        if (cb.isChecked()) {
            MapLayer ml = cb.getValue();
            if (layerDisplayNames.length() > 0) {
                layerDisplayNames += ", ";
            }
            layerDisplayNames += ml.getDisplayName();
            if (ml != null) {
                if (ml.getFacets() != null) {
                    facets.addAll(ml.getFacets());
                }
                try {
                    //get actual WKT when 'envelope' is specified
                    String w = ml.getWKT();
                    if (w.startsWith(StringConstants.ENVELOPE)) {
                        //should only be one pid
                        String pid = w.substring(w.indexOf(',') + 1, w.length() - 1);
                        w = Util.readUrl(CommonData.getLayersServer() + "/shape/wkt/" + pid);
                    }
                    Geometry g = wktReader.read(w);
                    if (g != null) {
                        wkt.add(g);
                    }
                } catch (ParseException e) {
                    LOGGER.error("cannot parse WKT for map layer: " + ml.getDisplayName() + " for WKT: " + ml.getWKT());
                }
            } else {
                String swkt = null;
                if (CommonData.getSettings().getProperty(CommonData.AUSTRALIA_NAME).equalsIgnoreCase(cb.getLabel())) {
                    swkt = CommonData.getSettings().getProperty(CommonData.AUSTRALIA_WKT);
                } else if ("Current Extent".equalsIgnoreCase(cb.getLabel())) {
                    swkt = getMapComposer().getViewArea();
                } else {
                    LOGGER.error("cannot determine what this checked area is: " + cb.getLabel());
                }
                if (swkt != null) {
                    try {
                        Geometry g = wktReader.read(swkt);
                        if (g != null) {
                            wkt.add(g);
                        }
                    } catch (ParseException e) {
                        LOGGER.error("cannot parse WKT for map layer: " + ml.getDisplayName() + " for WKT: " + swkt);
                    }
                }
            }
        }
    }
    //produce single geometry
    Geometry geometry = null;
    if (!wkt.isEmpty()) {
        geometry = wkt.get(0);
        for (int i = 1; i < wkt.size(); i++) {
            geometry = GeometryCombiner.combine(geometry, wkt.get(i));
        }
    }
    String finalWkt = (geometry == null) ? null : geometry.toString();
    MapComposer mc = getMapComposer();
    layerName = (mc.getMapLayer(txtLayerName.getValue()) == null) ? txtLayerName.getValue() : mc.getNextAreaLayerName(txtLayerName.getValue());
    MapLayer mapLayer = mc.addWKTLayer(finalWkt, layerName, txtLayerName.getValue());
    //if possible, use facets instead of WKT with biocache
    if (wkt.size() == facets.size()) {
        //change to a single OR facet.
        //Because all facet areas are single or multiple, ORs just need to OR for joining.
        String fq = facets.get(0).toString();
        for (int i = 1; i < facets.size(); i++) {
            fq += " OR " + facets.get(i).toString();
        }
        List<Facet> array = new ArrayList<Facet>();
        array.add(Facet.parseFacet(fq));
        mapLayer.setFacets(array);
    }
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    java.util.Calendar calendar = java.util.Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    String metadata = "";
    metadata += "Merged WKT layers\nLayers: " + layerDisplayNames + "\n";
    metadata += "Name: " + layerName + " <br />\n";
    metadata += "Date: " + formatter.format(calendar.getTime()) + " <br />\n";
    mapLayer.getMapLayerMetadata().setMoreInfo(metadata);
    //reapply layer name
    getMapComposer().getMapLayer(layerName).setDisplayName(txtLayerName.getValue());
    getMapComposer().redrawLayersList();
    ok = true;
    this.detach();
}
Also used : MapLayer(au.org.emii.portal.menu.MapLayer) ArrayList(java.util.ArrayList) WKTReader(com.vividsolutions.jts.io.WKTReader) Geometry(com.vividsolutions.jts.geom.Geometry) MapComposer(au.org.emii.portal.composer.MapComposer) Checkbox(org.zkoss.zul.Checkbox) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ParseException(com.vividsolutions.jts.io.ParseException) SimpleDateFormat(java.text.SimpleDateFormat) Facet(au.org.ala.legend.Facet)

Example 67 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project series-rest-api by 52North.

the class GeoJSONDecoder method decodeGeometryCollection.

protected GeometryCollection decodeGeometryCollection(JsonNode node, GeometryFactory fac) throws GeoJSONException {
    final JsonNode geometries = node.path(JSONConstants.GEOMETRIES);
    if (!geometries.isArray()) {
        throw new GeoJSONException("expected 'geometries' array");
    }
    Geometry[] geoms = new Geometry[geometries.size()];
    for (int i = 0; i < geometries.size(); ++i) {
        geoms[i] = decodeGeometry(geometries.get(i), fac);
    }
    return fac.createGeometryCollection(geoms);
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) JsonNode(com.fasterxml.jackson.databind.JsonNode) Point(com.vividsolutions.jts.geom.Point) MultiPoint(com.vividsolutions.jts.geom.MultiPoint)

Example 68 with Geometry

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

the class PointGenerationComposer method onFinish.

@Override
public boolean onFinish() {
    SelectedArea sa = getSelectedArea();
    double[][] bbox = null;
    if (sa.getMapLayer() != null && sa.getMapLayer().getMapLayerMetadata() != null) {
        List<Double> bb = sa.getMapLayer().getMapLayerMetadata().getBbox();
        bbox = new double[2][2];
        bbox[0][0] = bb.get(0);
        bbox[0][1] = bb.get(1);
        bbox[1][0] = bb.get(2);
        bbox[1][1] = bb.get(3);
    } else {
        List<Double> bb = Util.getBoundingBox(sa.getWkt());
        bbox = new double[][] { { bb.get(0), bb.get(1) }, { bb.get(2), bb.get(3) } };
    }
    //with bounding box, cut points
    try {
        String wkt = (sa.getMapLayer() != null ? sa.getMapLayer().getWKT() : sa.getWkt());
        StringBuilder sb = new StringBuilder();
        sb.append("longitude,latitude");
        int count = 0;
        int width = (int) Math.ceil((bbox[1][0] - bbox[0][0]) / resolution.getValue());
        int height = (int) Math.ceil((bbox[1][1] - bbox[0][1]) / resolution.getValue());
        double startx = Math.floor(bbox[0][0] / resolution.getValue()) * resolution.getValue();
        double starty = Math.floor(bbox[0][1] / resolution.getValue()) * resolution.getValue();
        if (wkt == null) {
            if (sa.getFacets() != null) {
                double[][] points = new double[(width + 1) * (height + 1)][2];
                int pos = 0;
                for (int i = 0; i <= width; i++) {
                    for (int j = 0; j <= height; j++) {
                        double lng = startx + i * resolution.getValue();
                        double lat = starty + j * resolution.getValue();
                        points[pos][0] = lng;
                        points[pos][1] = lat;
                        pos = pos + 1;
                    }
                }
                List<String> fields = new ArrayList<String>();
                for (Facet f : sa.getFacets()) {
                    fields.add(f.getFields()[0]);
                }
                List<String[]> result = Sampling.sampling(fields, points);
                for (int i = 0; i < result.size(); i++) {
                    Facet f = sa.getFacets().get(i);
                    String[] intersection = result.get(i);
                    for (int j = 0; j < intersection.length; j++) {
                        if (f.isValid("\"" + intersection[j] + "\"")) {
                            sb.append("\n");
                            sb.append(points[j][0]).append(",").append(points[j][1]);
                            count++;
                        }
                    }
                }
            } else {
                LOGGER.error("invalid area selected for point generation");
                getMapComposer().showMessage("Unsupported area selected for point generation. Choose a different area.");
                return false;
            }
        } else {
            //write temporary shapefile
            File tmp = File.createTempFile("tmp", ".shp");
            ShapefileUtils.saveShapefile(tmp, wkt, "tmp");
            FileDataStore store = FileDataStoreFinder.getDataStore(tmp);
            FeatureSource featureSource = store.getFeatureSource(store.getTypeNames()[0]);
            FeatureCollection featureCollection = featureSource.getFeatures();
            GeometryFactory gf = new GeometryFactory();
            List<Geometry> geometry = new ArrayList<Geometry>();
            FeatureIterator it = featureCollection.features();
            while (it.hasNext()) {
                SimpleFeature feature = (SimpleFeature) it.next();
                geometry.add((Geometry) feature.getDefaultGeometry());
            }
            try {
                it.close();
            } catch (Exception e) {
            }
            for (int i = 0; i <= width; i++) {
                for (int j = 0; j <= height; j++) {
                    double lng = startx + i * resolution.getValue();
                    double lat = starty + j * resolution.getValue();
                    Coordinate c = new Coordinate(lng, lat);
                    Geometry point = gf.createPoint(c);
                    for (Geometry geom : geometry) {
                        if (geom.contains(point)) {
                            sb.append("\n");
                            sb.append(lng).append(",").append(lat);
                            count++;
                        }
                    }
                }
            }
            //close tmp file
            try {
                store.dispose();
            } catch (Exception e) {
            }
            //delete tmp files
            try {
                FileUtils.deleteQuietly(tmp);
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".shx")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".fix")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".dbf")));
                FileUtils.deleteQuietly(new File(tmp.getPath().replace(".shp", ".prj")));
            } catch (Exception e) {
            }
        }
        if (count <= 0) {
            getMapComposer().showMessage("No points generated. Try again with a smaller resolution or larger area.");
        } else if (count > Integer.parseInt(CommonData.getSettings().getProperty("max_record_count_upload"))) {
            getMapComposer().showMessage(count + " points generated. Maximum is " + CommonData.getSettings().getProperty("generated_points_max") + ".\n" + "Try again with a larger resolution or smaller area.");
        } else {
            String name = tToolName.getValue();
            try {
                UploadSpeciesController.loadUserPoints(new UserDataDTO(name), new StringReader(sb.toString()), true, name, "points in " + getSelectedAreaDisplayName() + " on " + resolution.getValue() + " degree resolution grid.", getMapComposer(), null);
                detach();
                return true;
            } catch (Exception e) {
                LOGGER.error("failed to upload points");
            }
        }
    } catch (Exception e) {
    }
    return false;
}
Also used : GeometryFactory(com.vividsolutions.jts.geom.GeometryFactory) SelectedArea(au.org.emii.portal.menu.SelectedArea) ArrayList(java.util.ArrayList) FeatureIterator(org.geotools.feature.FeatureIterator) StringReader(java.io.StringReader) UserDataDTO(au.org.ala.spatial.dto.UserDataDTO) FileDataStore(org.geotools.data.FileDataStore) Facet(au.org.ala.legend.Facet) FeatureSource(org.geotools.data.FeatureSource) SimpleFeature(org.opengis.feature.simple.SimpleFeature) Geometry(com.vividsolutions.jts.geom.Geometry) FeatureCollection(org.geotools.feature.FeatureCollection) Coordinate(com.vividsolutions.jts.geom.Coordinate) File(java.io.File)

Example 69 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project ddf by codice.

the class GeospatialEvaluator method evaluate.

public static boolean evaluate(GeospatialEvaluationCriteria gec) {
    String methodName = "evaluate";
    LOGGER.debug("ENTERING: {}", methodName);
    String operation = gec.getOperation();
    Geometry input = gec.getInput();
    Geometry criteria = gec.getCriteria();
    double distance = gec.getDistance();
    LOGGER.debug("operation = {}", operation);
    boolean evaluation = false;
    if (distance == 0.0) {
        switch(SpatialOperator.valueOf(operation.toUpperCase())) {
            case CONTAINS:
                LOGGER.debug("Doing CONTAINS evaluation");
                evaluation = containsWithGeometryCollection(criteria, input);
                break;
            case OVERLAPS:
                LOGGER.debug("Doing OVERLAPS evaluation");
                evaluation = overlapsWithGeometryCollection(criteria, input);
                break;
            default:
                LOGGER.debug("Doing default evaluation - always false");
                evaluation = false;
                break;
        }
    } else {
        LOGGER.debug("Doing DISTANCE evaluation");
        // compare each geometry's closest distance to each other
        double distanceBetweenNearestPtsOnGeometries = DistanceOp.distance(input, criteria);
        LOGGER.debug("distanceBetweenNearestPtsOnGeometries = {},    distance = {}", distanceBetweenNearestPtsOnGeometries, distance);
        evaluation = distanceBetweenNearestPtsOnGeometries <= distance;
    }
    LOGGER.debug("evaluation = {}", evaluation);
    LOGGER.debug("EXITING: {}", methodName);
    return evaluation;
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry)

Example 70 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project ddf by codice.

the class BoundingBoxReader method convertToEPSG4326.

private String convertToEPSG4326(String wkt, String crs) throws CswException {
    try {
        Geometry geometry = wktReader.read(wkt);
        Geometry convertedGeometry = GeospatialUtil.transformToEPSG4326LonLatFormat(geometry, crs);
        if (convertedGeometry != null && withinEPSG4326Bounds(convertedGeometry)) {
            return WKT_WRITER_THREAD_LOCAL.get().write(convertedGeometry);
        } else {
            throw new GeoFormatException("Converted Geometry is not set, or not within EPSG4326 bounds");
        }
    } catch (ParseException | GeoFormatException e) {
        throw new CswException(String.format("Unable to convert %s from %s to EPSG:4326", wkt, crs));
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) GeoFormatException(org.codice.ddf.libs.geo.GeoFormatException) ParseException(com.vividsolutions.jts.io.ParseException)

Aggregations

Geometry (com.vividsolutions.jts.geom.Geometry)125 WKTReader (com.vividsolutions.jts.io.WKTReader)35 Test (org.junit.Test)31 Coordinate (com.vividsolutions.jts.geom.Coordinate)24 Point (com.vividsolutions.jts.geom.Point)21 ParseException (com.vividsolutions.jts.io.ParseException)19 GeometryFactory (com.vividsolutions.jts.geom.GeometryFactory)14 CoordinateReferenceSystem (org.opengis.referencing.crs.CoordinateReferenceSystem)14 Envelope (com.vividsolutions.jts.geom.Envelope)13 WKTWriter (com.vividsolutions.jts.io.WKTWriter)13 ArrayList (java.util.ArrayList)13 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