Search in sources :

Example 56 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project elasticsearch by elastic.

the class RandomShapeGenerator method createShape.

/**
     * Creates a random shape useful for randomized testing, NOTE: exercise caution when using this to build random GeometryCollections
     * as creating a large random number of random shapes can result in massive resource consumption
     * see: {@link GeoShapeQueryTests#testShapeFilterWithRandomGeoCollection}
     *
     * The following options are included
     * @param nearPoint Create a shape near a provided point
     * @param within Create a shape within the provided rectangle (note: if not null this will override the provided point)
     * @param st Create a random shape of the provided type
     * @return the ShapeBuilder for a random shape
     */
private static ShapeBuilder createShape(Random r, Point nearPoint, Rectangle within, ShapeType st, boolean validate) throws InvalidShapeException {
    if (st == null) {
        st = ShapeType.randomType(r);
    }
    if (within == null) {
        within = xRandomRectangle(r, nearPoint);
    }
    // inside non overlapping bounding rectangles
    switch(st) {
        case POINT:
            Point p = xRandomPointIn(r, within);
            PointBuilder pb = new PointBuilder().coordinate(new Coordinate(p.getX(), p.getY(), Double.NaN));
            return pb;
        case MULTIPOINT:
        case LINESTRING:
            // for random testing having a maximum number of 10 points for a line string is more than sufficient
            // if this number gets out of hand, the number of self intersections for a linestring can become
            // (n^2-n)/2 and computing the relation intersection matrix will become NP-Hard
            int numPoints = RandomNumbers.randomIntBetween(r, 3, 10);
            CoordinatesBuilder coordinatesBuilder = new CoordinatesBuilder();
            for (int i = 0; i < numPoints; ++i) {
                p = xRandomPointIn(r, within);
                coordinatesBuilder.coordinate(p.getX(), p.getY());
            }
            CoordinateCollection pcb = (st == ShapeType.MULTIPOINT) ? new MultiPointBuilder(coordinatesBuilder.build()) : new LineStringBuilder(coordinatesBuilder);
            return pcb;
        case MULTILINESTRING:
            MultiLineStringBuilder mlsb = new MultiLineStringBuilder();
            for (int i = 0; i < RandomNumbers.randomIntBetween(r, 1, 10); ++i) {
                mlsb.linestring((LineStringBuilder) createShape(r, nearPoint, within, ShapeType.LINESTRING, false));
            }
            return mlsb;
        case POLYGON:
            numPoints = RandomNumbers.randomIntBetween(r, 5, 25);
            Coordinate[] coordinates = new Coordinate[numPoints];
            for (int i = 0; i < numPoints; ++i) {
                p = (Point) createShape(r, nearPoint, within, ShapeType.POINT, false).build();
                coordinates[i] = new Coordinate(p.getX(), p.getY());
            }
            // random point order or random linestrings can lead to invalid self-crossing polygons,
            // compute the convex hull for a set of points to ensure polygon does not self cross
            Geometry shell = new ConvexHull(coordinates, ctx.getGeometryFactory()).getConvexHull();
            Coordinate[] shellCoords = shell.getCoordinates();
            // when all else fails, use the bounding box as the polygon
            if (shellCoords.length < 3) {
                shellCoords = new Coordinate[4];
                shellCoords[0] = new Coordinate(within.getMinX(), within.getMinY());
                shellCoords[1] = new Coordinate(within.getMinX(), within.getMaxY());
                shellCoords[2] = new Coordinate(within.getMaxX(), within.getMaxY());
                shellCoords[3] = new Coordinate(within.getMaxX(), within.getMinY());
            }
            PolygonBuilder pgb = new PolygonBuilder(new CoordinatesBuilder().coordinates(shellCoords).close());
            if (validate) {
                // The validate flag will check for these possibilities and bail if an incorrect geometry is created
                try {
                    pgb.build();
                } catch (AssertionError | InvalidShapeException e) {
                    // or InvalidShapeException
                    return null;
                }
            }
            return pgb;
        default:
            throw new ElasticsearchException("Unable to create shape of type [" + st + "]");
    }
}
Also used : InvalidShapeException(org.locationtech.spatial4j.exception.InvalidShapeException) ConvexHull(com.vividsolutions.jts.algorithm.ConvexHull) Point(org.locationtech.spatial4j.shape.Point) ElasticsearchException(org.elasticsearch.ElasticsearchException) MultiPointBuilder(org.elasticsearch.common.geo.builders.MultiPointBuilder) Point(org.locationtech.spatial4j.shape.Point) LineStringBuilder(org.elasticsearch.common.geo.builders.LineStringBuilder) MultiLineStringBuilder(org.elasticsearch.common.geo.builders.MultiLineStringBuilder) Geometry(com.vividsolutions.jts.geom.Geometry) CoordinatesBuilder(org.elasticsearch.common.geo.builders.CoordinatesBuilder) PointBuilder(org.elasticsearch.common.geo.builders.PointBuilder) MultiPointBuilder(org.elasticsearch.common.geo.builders.MultiPointBuilder) Coordinate(com.vividsolutions.jts.geom.Coordinate) MultiLineStringBuilder(org.elasticsearch.common.geo.builders.MultiLineStringBuilder) CoordinateCollection(org.elasticsearch.common.geo.builders.CoordinateCollection) PolygonBuilder(org.elasticsearch.common.geo.builders.PolygonBuilder)

Example 57 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project elasticsearch by elastic.

the class ElasticsearchGeoAssertions method assertEquals.

public static void assertEquals(MultiPolygon p1, MultiPolygon p2) {
    Assert.assertEquals(p1.getNumGeometries(), p2.getNumGeometries());
    // if the inner polygons are not ordered the same way in both Multipolygons
    for (int i = 0; i < p1.getNumGeometries(); i++) {
        Geometry a = p1.getGeometryN(i);
        Geometry b = p2.getGeometryN(i);
        assertEquals(a, b);
    }
}
Also used : JtsGeometry(org.locationtech.spatial4j.shape.jts.JtsGeometry) Geometry(com.vividsolutions.jts.geom.Geometry) GeoPoint(org.elasticsearch.common.geo.GeoPoint) JtsPoint(org.locationtech.spatial4j.shape.jts.JtsPoint) MultiPoint(com.vividsolutions.jts.geom.MultiPoint)

Example 58 with Geometry

use of com.vividsolutions.jts.geom.Geometry in project hibernate-orm by hibernate.

the class GeomEntity method createFrom.

public static GeomEntity createFrom(TestDataElement element) throws ParseException {
    WktDecoder decoder = Wkt.newDecoder(Wkt.Dialect.POSTGIS_EWKT_1);
    Geometry geom = JTS.to(decoder.decode(element.wkt));
    GeomEntity result = new GeomEntity();
    result.setId(element.id);
    result.setGeom(geom);
    result.setType(element.type);
    return result;
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) WktDecoder(org.geolatte.geom.codec.WktDecoder)

Example 59 with Geometry

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

the class ExportLayerComposer method exportAreaAs.

public void exportAreaAs(String type, String name, SelectedArea sa) {
    String exportBaseDir = CommonData.getSettings().getProperty(StringConstants.ANALYSIS_OUTPUT_DIR) + File.separator + "export" + File.separator;
    try {
        String id = String.valueOf(System.currentTimeMillis());
        File shpDir = new File(exportBaseDir + id + File.separator);
        shpDir.mkdirs();
        File shpfile;
        String contentType = LayersUtil.LAYER_TYPE_ZIP;
        String outfile = name.replaceAll(" ", "_");
        if ("shp".equals(type)) {
            shpfile = new File(exportBaseDir + id + File.separator + outfile + "_Shapefile.shp");
            ShapefileUtils.saveShapefile(shpfile, sa.getWkt(), name);
            outfile += "_SHP.zip";
        } else if ("kml".equals(type)) {
            StringBuilder sbKml = new StringBuilder();
            sbKml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("\r");
            sbKml.append("<kml xmlns=\"http://earth.google.com/kml/2.2\">").append("\r");
            sbKml.append("<Document>").append("\r");
            sbKml.append("  <name>Spatial Portal Active Area</name>").append("\r");
            sbKml.append("  <description><![CDATA[Active area saved from the ALA Spatial Portal: http://spatial.ala.org.au/]]></description>").append("\r");
            sbKml.append("  <Style id=\"style1\">").append("\r");
            sbKml.append("    <LineStyle>").append("\r");
            sbKml.append("      <color>40000000</color>").append("\r");
            sbKml.append("      <width>3</width>").append("\r");
            sbKml.append("    </LineStyle>").append("\r");
            sbKml.append("    <PolyStyle>").append("\r");
            sbKml.append("      <color>73FF0000</color>").append("\r");
            sbKml.append("      <fill>1</fill>").append("\r");
            sbKml.append("      <outline>1</outline>").append("\r");
            sbKml.append("    </PolyStyle>").append("\r");
            sbKml.append("  </Style>").append("\r");
            sbKml.append("  <Placemark>").append("\r");
            sbKml.append("    <name>").append(name).append("</name>").append("\r");
            sbKml.append("    <description><![CDATA[<div dir=\"ltr\">").append(name).append("<br></div>]]></description>").append("\r");
            sbKml.append("    <styleUrl>#style1</styleUrl>").append("\r");
            //Remove first line of kmlGeometry, <?xml...>
            Geometry geom = new WKTReader().read(sa.getWkt());
            Encoder encoder = new Encoder(new KMLConfiguration());
            encoder.setIndenting(true);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            encoder.encode(geom, KML.Geometry, baos);
            String kmlGeometry = new String(baos.toByteArray());
            sbKml.append(kmlGeometry.substring(kmlGeometry.indexOf("?>") + 2));
            sbKml.append("  </Placemark>").append("\r");
            sbKml.append("</Document>").append("\r");
            sbKml.append("</kml>").append("\r");
            shpfile = new File(exportBaseDir + id + File.separator + outfile + "_KML.kml");
            BufferedWriter wout = new BufferedWriter(new FileWriter(shpfile));
            wout.write(sbKml.toString());
            wout.close();
            outfile += "_KML.zip";
        } else if (StringConstants.WKT.equals(type)) {
            shpfile = new File(exportBaseDir + id + File.separator + outfile + "_WKT.txt");
            BufferedWriter wout = new BufferedWriter(new FileWriter(shpfile));
            wout.write(sa.getWkt());
            wout.close();
            outfile += "_WKT.zip";
        }
        //zip shpfile
        Zipper.zipDirectory(exportBaseDir + id + File.separator, exportBaseDir + id + ".zip");
        try {
            byte[] bytes = FileUtils.readFileToByteArray(new File(exportBaseDir + id + ".zip"));
            Filedownload.save(bytes, contentType, outfile);
        } catch (Exception e) {
            LOGGER.error("failed to download file : " + exportBaseDir + id + ".zip", e);
        }
        try {
            remoteLogger.logMapAnalysis(name, "Export - " + StringUtils.capitalize(type) + " Area", sa.getWkt(), "", "", "", outfile, "download");
        } catch (Exception e) {
            LOGGER.error("remote logger error", e);
        }
    } catch (Exception e) {
        LOGGER.error("Unable to export user area", e);
    }
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) Encoder(org.geotools.xml.Encoder) FileWriter(java.io.FileWriter) KMLConfiguration(org.geotools.kml.KMLConfiguration) ByteArrayOutputStream(java.io.ByteArrayOutputStream) WKTReader(com.vividsolutions.jts.io.WKTReader) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 60 with Geometry

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

the class BiocacheQuery method newWkt.

/**
     * Restrict to an area.
     * <p/>
     * If an area already exists the additional area is applied.
     *
     * @param wkt
     * @return new BiocacheQuery with the additional wkt area applied.
     */
@Override
public BiocacheQuery newWkt(String wkt, boolean forMapping) {
    if (wkt == null || wkt.equals(CommonData.WORLD_WKT) || wkt.equals(this.wkt)) {
        if (this.forMapping || !forMapping) {
            return this;
        } else {
            return new BiocacheQuery(lsids, rawNames, wkt, extraParams, facets, forMapping, null, biocacheServer, biocacheWebServer, this.supportsDynamicFacets);
        }
    }
    BiocacheQuery sq = null;
    try {
        String newWkt = wkt;
        if (this.wkt != null) {
            Geometry newGeom = new WKTReader().read(wkt);
            Geometry thisGeom = new WKTReader().read(this.wkt);
            Geometry intersectionGeom = thisGeom.intersection(newGeom);
            newWkt = (new WKTWriter()).write(intersectionGeom).replace(" (", "(").replace(", ", ",").replace(") ", ")");
        }
        sq = new BiocacheQuery(lsids, rawNames, newWkt, extraParams, facets, forMapping, null, biocacheServer, biocacheWebServer, this.supportsDynamicFacets);
    } catch (Exception e) {
        LOGGER.error("error getting new WKT from an intersection", e);
    }
    return sq;
}
Also used : Geometry(com.vividsolutions.jts.geom.Geometry) WKTWriter(com.vividsolutions.jts.io.WKTWriter) WKTReader(com.vividsolutions.jts.io.WKTReader)

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