org.locationtech.jts.io.WKTReader Java Examples

The following examples show how to use org.locationtech.jts.io.WKTReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VectorTileEncoder.java    From java-vector-tile with Apache License 2.0 6 votes vote down vote up
/**
 * Clip geometry according to buffer given at construct time. This method
 * can be overridden to change clipping behavior. See also
 * {@link #clipCovers(Geometry)}.
 *
 * @param geometry
 * @return
 */
protected Geometry clipGeometry(Geometry geometry) {
    try {
        Geometry original = geometry;
        geometry = clipGeometry.intersection(original);

        // some times a intersection is returned as an empty geometry.
        // going via wkt fixes the problem.
        if (geometry.isEmpty() && original.intersects(clipGeometry)) {
            Geometry originalViaWkt = new WKTReader().read(original.toText());
            geometry = clipGeometry.intersection(originalViaWkt);
        }

        return geometry;
    } catch (TopologyException e) {
        // could not intersect. original geometry will be used instead.
        return geometry;
    } catch (ParseException e1) {
        // could not encode/decode WKT. original geometry will be used
        // instead.
        return geometry;
    }
}
 
Example #2
Source File: ShapeConverter.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object parse(String text) throws ConversionException {
    try {
        Geometry geometry = new WKTReader(geometryFactory).read(text);
        if (geometry instanceof LineString) {
            LineString lineString = (LineString) geometry;
            // todo
            return null;
        } else if (geometry instanceof Polygon) {
            Polygon polygon = (Polygon) geometry;
            // todo
            return null;
        } else {
            throw new ConversionException("Failed to parse shape geometry WKT.");
        }
    } catch (ParseException e) {
        throw new ConversionException("Failed to parse shape geometry WKT.", e);
    }
}
 
Example #3
Source File: TestGeometryUtilities.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
public void testLineMerger() throws Exception {
    String l1 = "LINESTRING (0 300, 200 300, 200 200)";
    String l2 = "LINESTRING (200 0, 200 200)";
    String l3 = "LINESTRING (50 100, 250 100, 300 100)";
    String l4 = "LINESTRING (300 100, 300 0)";
    String l5 = "LINESTRING (50 100, 50 0, 200 0)";

    WKTReader r = new WKTReader();
    LineString g1 = (LineString) r.read(l1);
    LineString g2 = (LineString) r.read(l2);
    LineString g3 = (LineString) r.read(l3);
    LineString g4 = (LineString) r.read(l4);
    LineString g5 = (LineString) r.read(l5);

    List<LineString> mergeLinestrings = GeometryUtilities.mergeLinestrings(Arrays.asList(g1, g2, g3, g4));
    assertEquals(2, mergeLinestrings.size());
    mergeLinestrings = GeometryUtilities.mergeLinestrings(Arrays.asList(g1, g2, g3, g4, g5));
    assertEquals(1, mergeLinestrings.size());

}
 
Example #4
Source File: TestSpatialDbsMain.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSpatialiteWKBReadWrite() throws Exception {
    String polygonStr = "POLYGON ((71 70, 40 70, 40 40, 5 40, 5 15, 15 15, 15 4, 50 4, 71 70))";
    Geometry geom = new WKTReader().read(polygonStr);
    checkReadWrite(geom);

    String gCollWKT = "GEOMETRYCOLLECTION (" //
            + " POLYGON ((10 42, 11.9 42, 11.9 40, 10 40, 10 42)), "
            + " POLYGON ((11.1 43.2, 11.3 41.3, 13.9 41, 13.8 43.2, 11.1 43.2)), "
            + " LINESTRING (11.3 44.3, 8.3 41.4, 11.4 38.1, 14.9 41.3), " //
            + " POINT (12.7 44.2), " //
            + " POINT (15.1 43.3), " //
            + " POINT (15 40.4), " //
            + " POINT (13.2 38.4), "
            + " MULTIPOLYGON (((6.9 45.9, 8.4 45.9, 8.4 44.3, 6.9 44.3, 6.9 45.9)), ((9.1 46.3, 10.8 46.3, 10.8 44.6, 9.1 44.6, 9.1 46.3))), "
            + " MULTILINESTRING ((7.4 42.6, 7.4 39, 8.6 38.5), (8 40.3, 9.5 38.6, 8.4 37.5)), "
            + " MULTIPOINT ((6.8 42.5), (6.8 41.4), (6.6 40.2)))";
    geom = new WKTReader().read(gCollWKT);
    checkReadWrite(geom);

}
 
Example #5
Source File: H2IndexingAbstractGeoSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception If failed.
 */
@Test
public void testPrimitiveGeometry() throws Exception {
    IgniteCache<Long, Geometry> cache = createCache("geom", true, Long.class, Geometry.class);

    try {
        WKTReader r = new WKTReader();

        for (long i = 0; i < 100; i++)
            cache.put(i, r.read("POINT(" + i + " " + i + ")"));

        String plan = cache.query(new SqlFieldsQuery("explain select _key from Geometry where _val && ?")
            .setArgs(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))")).setLocal(true))
            .getAll().get(0).get(0).toString().toLowerCase();

        assertTrue("__ explain: " + plan, plan.contains("_val_idx"));
    }
    finally {
        cache.destroy();
    }
}
 
Example #6
Source File: TestSpatialDbsMain.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIntersectsPolygon() throws Exception {
    String polygonStr = "POLYGON ((71 70, 40 70, 40 40, 5 40, 5 15, 15 15, 15 4, 50 4, 71 70))";
    Geometry geom = new WKTReader().read(polygonStr);
    List<Geometry> intersecting = db.getGeometriesIn(MPOLY_TABLE, geom);
    assertEquals(2, intersecting.size());
}
 
Example #7
Source File: TestGeometrySerialization.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Geometry createJtsGeometry(String wkt)
{
    try {
        return new WKTReader().read(wkt);
    }
    catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
Example #8
Source File: TestSpatialDbsMain.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testReprojectFromDb() throws Exception {

    double w = 11.143413001499738;
    double e = 11.147502220729288;
    double s = 46.62897848892326;
    double n = 46.62981208577648;

    Envelope env = new Envelope(w, e, s, n);
    
    Envelope reprojected = db.reproject(env, 4326, 32632);
    double rw = reprojected.getMinX();
    double re = reprojected.getMaxX();
    double rs = reprojected.getMinY();
    double rn = reprojected.getMaxY();
    
    assertEquals(664076.6777860201, rw, 0.001);
    assertEquals(664387.1714802807, re, 0.001);
    assertEquals(5166166.626361137, rs, 0.001);
    assertEquals(5166267.775614383, rn, 0.001);
    
    
    
    WKTReader reader = new WKTReader();
    Geometry point = reader.read("POINT (11.143413001499738 46.62897848892326)");
    Geometry reprojectedGeom = db.reproject(point, 4326, 32632);
    Geometry expected = reader.read("POINT (664076.6777860201 5166166.626361137)");
    
    double distance = reprojectedGeom.distance(expected);
    assertEquals(0.0, distance, 0.00001);
    
}
 
Example #9
Source File: RESTRuleServiceImpl.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected LayerDetails detailsFromInput(RESTInputRule in) {
    RESTLayerConstraints constraints = in.getConstraints();
    if (constraints != null) {
        LayerDetails details = new LayerDetails();

        if (constraints.getAllowedStyles() != null) {
            details.setAllowedStyles(new HashSet(constraints.getAllowedStyles()));
        }
        if (constraints.getAttributes() != null) {
            details.setAttributes(new HashSet(constraints.getAttributes()));
        }
        details.setCqlFilterRead(constraints.getCqlFilterRead());
        details.setCqlFilterWrite(constraints.getCqlFilterWrite());
        details.setDefaultStyle(constraints.getDefaultStyle());
        if (constraints.getRestrictedAreaWkt() != null) {
            WKTReader reader = new WKTReader();
            Geometry g;
            try {
                g = reader.read(constraints.getRestrictedAreaWkt());
            } catch (ParseException ex) {
                throw new BadRequestRestEx("Error parsing WKT:" + ex.getMessage());
            }
            details.setArea((MultiPolygon) g);
        }

        details.setType(constraints.getType());

        return details;
    } else {
        return null;
    }
}
 
Example #10
Source File: RuleReaderServiceImplTest.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected MultiPolygon buildMultiPolygon(String multip) {
    try {
        WKTReader reader = new WKTReader();
        MultiPolygon mp = (MultiPolygon) reader.read(multip);
        mp.setSRID(4326);
        return mp;
    } catch (ParseException ex) {
        throw new RuntimeException("Unexpected exception: " + ex.getMessage(), ex);
    }
}
 
Example #11
Source File: ServiceTestBase.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected MultiPolygon parseMultiPolygon(String wkt) {
    try {
        WKTReader wktReader = new WKTReader();
        MultiPolygon the_geom = (MultiPolygon) wktReader.read(wkt);
        the_geom.setSRID(4326);
        return the_geom;
    } catch (ParseException e) {
        throw new IllegalArgumentException("Unparsabe WKT", e);
    }
}
 
Example #12
Source File: BaseDAOTest.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected MultiPolygon buildMultiPolygon() {
    try {
        WKTReader reader = new WKTReader();
        MultiPolygon mp = (MultiPolygon) reader.read(MULTIPOLYGONWKT);
        mp.setSRID(4326);
        return mp;
    } catch (ParseException ex) {
        throw new RuntimeException("Unexpected exception: " + ex.getMessage(), ex);
    }
}
 
Example #13
Source File: BaseDAOTest.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
protected Polygon buildPolygon() {
    try {
        WKTReader reader = new WKTReader();
        Polygon mp = (Polygon) reader.read(POLYGONWKT);
        mp.setSRID(4326);
        return mp;
    } catch (ParseException ex) {
        throw new RuntimeException("Unexpected exception: " + ex.getMessage(), ex);
    }
}
 
Example #14
Source File: GeometryAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public G unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom.getSRID() == 0)
        the_geom.setSRID(4326);

    try {
        return (G) the_geom;
    } catch (ClassCastException e) {
        throw new ParseException("WKT val is a " + the_geom.getClass().getName());
    }
}
 
Example #15
Source File: PolygonAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Polygon unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom instanceof Polygon) {
        if (the_geom.getSRID() == 0)
            the_geom.setSRID(4326);

        return (Polygon) the_geom;
    }

    throw new ParseException("WKB val is not a Polygon.");
}
 
Example #16
Source File: XMultiPolygonAdapter.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
@Override
public MultiPolygon unmarshal(String val) throws ParseException {
    WKTReader wktReader = new WKTReader();

    Geometry the_geom = wktReader.read(val);
    if (the_geom.getSRID() == 0)
        the_geom.setSRID(4326);

    try {
        return (MultiPolygon) the_geom;
    } catch (ClassCastException e) {
        throw new ParseException("WKT val is a " + the_geom.getClass().getName());
    }
}
 
Example #17
Source File: GeometryUtility.java    From geofence with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Project geometry.
 *
 * @param originalGeom
 *            the original geom
 * @param srcCRSCode
 *            the src crs code
 * @param trgCRSCode
 *            the trg crs code
 * @return the geometry
 * @throws NoSuchAuthorityCodeException
 *             the no such authority code exception
 * @throws FactoryException
 *             the factory exception
 * @throws MismatchedDimensionException
 *             the mismatched dimension exception
 * @throws TransformException
 *             the transform exception
 */
public static Geometry projectGeometry(Geometry originalGeom, String srcCRSCode,
    String trgCRSCode) throws NoSuchAuthorityCodeException, FactoryException, MismatchedDimensionException,
    TransformException
{

    Geometry projectedGeometry = null;
    final MathTransform transform = CRS.findMathTransform(CRS.decode(srcCRSCode, true), CRS.decode(trgCRSCode, true), true);

    // converting geometries into a linear system
    try
    {
        projectedGeometry = JTS.transform(originalGeom, transform);
    }
    catch (Exception e)
    {
        GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(
                    PrecisionModel.FLOATING), 4326);
        WKTReader reader = new WKTReader(geometryFactory);

        try
        {
            Polygon worldCutPolygon = (Polygon) reader.read("POLYGON((-180 -89.9, -180 89.9, 180 89.9, 180 -89.9, -180 -89.9))");

            projectedGeometry = JTS.transform(originalGeom.intersection(worldCutPolygon),
                    transform);
        }
        catch (Exception ex)
        {
            throw new RuntimeException(ex);
        }
    }

    return projectedGeometry;
}
 
Example #18
Source File: SubsetUI.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void updateGeoRegion() {
    try {
        geoRegion = new WKTReader().read(geoText.getText());

        final Coordinate coord[] = geoRegion.getCoordinates();
        worldMapUI.setSelectionStart((float) coord[0].y, (float) coord[0].x);
        worldMapUI.setSelectionEnd((float) coord[2].y, (float) coord[2].x);
        worldMapUI.getWorlMapPane().revalidate();
        worldMapUI.getWorlMapPane().getLayerCanvas().updateUI();
    } catch (Exception e) {
        SnapApp.getDefault().handleError("UpdateGeoRegion error reading wkt", e);
    }
}
 
Example #19
Source File: BinningFormModel.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
Geometry toGeometry(String wkt) {
    try {
        return new WKTReader().read(wkt);
    } catch (ParseException e) {
        throw new IllegalStateException("WKT for region is not valid:\n" + wkt);
    }
}
 
Example #20
Source File: PointConverter.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object parse(String text) throws ConversionException {
    try {
        Geometry geometry = new WKTReader(geometryFactory).read(text);
        if (geometry instanceof org.locationtech.jts.geom.Point) {
            org.locationtech.jts.geom.Point point = (org.locationtech.jts.geom.Point) geometry;
            return new Point2D.Double(point.getX(), point.getY());
        } else {
            throw new ConversionException("Failed to parse point geometry WKT.");
        }
    } catch (ParseException e) {
        throw new ConversionException("Failed to parse point geometry WKT.", e);
    }
}
 
Example #21
Source File: TestGeometryUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testPolygonToUnitScaler() throws Exception {
    WKTReader reader = new WKTReader();
    Geometry geometry = reader.read(IRREGULAR_POLYGON);
    Geometry scaled = GeometryUtilities.scaleToUnitaryArea((Polygon) geometry);
    double area = scaled.getArea();
    assertEquals(1.0, area, DELTA);

    geometry = reader.read(TWO_BALLS);
    scaled = GeometryUtilities.scaleToUnitaryArea((Polygon) geometry);
    area = scaled.getArea();
    assertEquals(1.0, area, DELTA);

    geometry = reader.read(RECTANGLE);
    scaled = GeometryUtilities.scaleToUnitaryArea((Polygon) geometry);
    area = scaled.getArea();
    assertEquals(1.0, area, DELTA);
    double perim = scaled.getLength();
    assertEquals(4.0, perim, DELTA);

    // hexa
    geometry = reader.read(HEXAGON);
    scaled = GeometryUtilities.scaleToUnitaryArea((Polygon) geometry);
    area = scaled.getArea();
    assertEquals(1.0, area, DELTA);
    perim = scaled.getLength();
    assertEquals(3.72241943, perim, DELTA);

    // triangle
    geometry = reader.read(EQUILATERAL_TRIANGLE);
    scaled = GeometryUtilities.scaleToUnitaryArea((Polygon) geometry);
    area = scaled.getArea();
    assertEquals(1.0, area, DELTA);
    perim = scaled.getLength();
    assertEquals(4.55901411, perim, DELTA);

}
 
Example #22
Source File: TestLineSmootherMcMaster.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorReader() throws Exception {

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName("test");
        b.setCRS(DefaultGeographicCRS.WGS84);
        b.add("the_geom", LineString.class);
        b.add("id", Integer.class);

        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
        SimpleFeatureType type = b.buildFeatureType();

        Geometry line = new WKTReader().read("LINESTRING (0 0, 1 1, 2 2, 3 3, 4 4, 5 3, 6 2, 7 1, 8 0)");
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Object[] values = new Object[]{line, 0};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
        newCollection.add(feature);

        OmsLineSmootherMcMaster smoother = new OmsLineSmootherMcMaster();
        smoother.inVector = newCollection;
        smoother.pLookahead = 3;
        smoother.pSlide = 0.9;
        smoother.pDensify = 0.9;
        smoother.process();
        SimpleFeatureCollection outFeatures = smoother.outVector;

        List<Geometry> geomList = FeatureUtilities.featureCollectionToGeometriesList(outFeatures, false, null);
        Geometry geometry = geomList.get(0);

        int newLength = geometry.getCoordinates().length;

        Geometry densifiedline = new WKTReader()
                .read("LINESTRING (0 0, 0.5 0.5, 1 1, 1.5 1.5, 2 2, 2.5 2.5, 3 3, 3.5 3.5, 4 4, 4.5 3.5, 5 3, 5.5 2.5, 6 2, 6.5 1.5, 7 1, 7.5 0.5, 8 0)");
        int expectedLength = densifiedline.getCoordinates().length;

        assertEquals(expectedLength, newLength);

    }
 
Example #23
Source File: TestLineSmootherJaitools.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public void testVectorReader() throws Exception {

        SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
        b.setName("test");
        b.setCRS(DefaultGeographicCRS.WGS84);
        b.add("the_geom", LineString.class);
        b.add("id", Integer.class);

        DefaultFeatureCollection newCollection = new DefaultFeatureCollection();
        SimpleFeatureType type = b.buildFeatureType();

        Geometry line = new WKTReader().read("LINESTRING (0 0, 1 1, 2 0)");//2 2, 3 3, 4 4, 5 3, 6 2, 7 1, 8 0)");
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(type);
        Object[] values = new Object[]{line, 0};
        builder.addAll(values);
        SimpleFeature feature = builder.buildFeature(type.getTypeName() + ".0");
        newCollection.add(feature);

        OmsLineSmootherJaitools smoother = new OmsLineSmootherJaitools();
        smoother.inVector = newCollection;
        smoother.pAlpha = 1;
        smoother.process();
        SimpleFeatureCollection outFeatures = smoother.outVector;

        List<Geometry> geomList = FeatureUtilities.featureCollectionToGeometriesList(outFeatures, false, null);
        Geometry geometry = geomList.get(0);
        
        int newLength = geometry.getCoordinates().length;

        Geometry densifiedline = new WKTReader()
                .read("LINESTRING (0 0, 0.0342935528120713 0.0342935528120713, 0.1262002743484225 0.1262002743484225, 0.2592592592592592 0.2592592592592592, 0.4170096021947873 0.4170096021947873, 0.5829903978052127 0.5829903978052127, 0.7407407407407407 0.7407407407407407, 0.8737997256515775 0.8737997256515775, 0.9657064471879286 0.9657064471879286, 1 1, 1.0342935528120714 0.9657064471879288, 1.1262002743484225 0.8737997256515775, 1.2592592592592593 0.7407407407407408, 1.4170096021947873 0.5829903978052127, 1.5829903978052127 0.4170096021947874, 1.7407407407407407 0.2592592592592593, 1.8737997256515775 0.1262002743484225, 1.9657064471879289 0.0342935528120714, 2 0)");
        int expectedLength = densifiedline.getCoordinates().length;

        assertEquals(expectedLength, newLength);

    }
 
Example #24
Source File: BenchmarkJtsGeometrySerde.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Geometry fromText(String text)
{
    try {
        return new WKTReader().read(text);
    }
    catch (ParseException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: H2IndexingAbstractGeoSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Check distributed query.
 *
 * @throws ParseException If failed.
 */
private void checkDistributedQuery() throws ParseException {
    IgniteCache<Integer, Enemy> c1 = grid(0).cache("enemy");
    IgniteCache<Integer, EnemyCamp> c2 = grid(0).cache("camp");

    final Geometry lethalArea = new WKTReader().read("POLYGON((30 30, 30 70, 70 70, 70 30, 30 30))");

    int expectedEnemies = 0;

    for (Cache.Entry<Integer, Enemy> e : c1) {
        final Integer campID = e.getValue().campId;

        if (30 <= campID && campID < ENEMYCAMP_SAMPLES_COUNT) {
            final EnemyCamp camp = c2.get(campID);

            if (lethalArea.covers(camp.coords))
                expectedEnemies++;
        }
    }

    final SqlFieldsQuery query = new SqlFieldsQuery("select e._val, c._val from \"enemy\".Enemy e, " +
        "\"camp\".EnemyCamp c where e.campId = c._key and c.coords && ?").setArgs(lethalArea);

    List<List<?>> result = c1.query(query.setDistributedJoins(true)).getAll();

    assertEquals(expectedEnemies, result.size());
}
 
Example #26
Source File: H2IndexingAbstractGeoSelfTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Check segmented geo-index join.
 *
 * @param partitioned Partitioned flag.
 * @param dynamic Whether index should be created dynamically.
 * @throws Exception If failed.
 */
private void checkSegmentedGeoIndexJoin(boolean partitioned, boolean dynamic) throws Exception {
    IgniteCache<Integer, Enemy> c1 = createCache("enemy", true, Integer.class, Enemy.class);
    IgniteCache<Integer, EnemyCamp> c2 = createCache("camp", partitioned, Integer.class, EnemyCamp.class, dynamic);

    try {
        final ThreadLocalRandom rnd = ThreadLocalRandom.current();

        WKTReader r = new WKTReader();

        for (int i = 0; i < ENEMYCAMP_SAMPLES_COUNT; i++) {
            final String point = String.format("POINT(%d %d)", rnd.nextInt(100), rnd.nextInt(100));

            c2.put(i, new EnemyCamp(r.read(point), "camp-" + i));
        }

        for (int i = 0; i < ENEMY_SAMPLES_COUNT; i++) {
            int campID = 30 + rnd.nextInt(ENEMYCAMP_SAMPLES_COUNT + 10);

            c1.put(i, new Enemy(campID, "enemy-" + i));
        }

        checkDistributedQuery();
    }
    finally {
        destroy(c1, grid(0), dynamic);
        destroy(c2, grid(0), dynamic);
    }
}
 
Example #27
Source File: TestPostgisDbsMain.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testIntersectsPolygon() throws Exception {
    String polygonStr = "POLYGON ((71 70, 40 70, 40 40, 5 40, 5 15, 15 15, 15 4, 50 4, 71 70))";
    Geometry geom = new WKTReader().read(polygonStr);
    List<Geometry> intersecting = db.getGeometriesIn(MPOLY_TABLE, geom);
    assertEquals(2, intersecting.size());
}
 
Example #28
Source File: WKTConversion.java    From sldeditor with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Convert to org.locationtech.jts.geom geometry.
 *
 * @param wktString the wkt string
 * @param crsCode the crs code
 * @return the geometry
 */
public static Geometry convertToGeometry(String wktString, String crsCode) {
    int srid = 0;

    if (crsCode != null) {
        CoordinateReferenceSystem crs = CoordManager.getInstance().getCRS(crsCode);
        String sridString = CRS.toSRS(crs, true);
        srid = Integer.parseInt(sridString);
    }
    org.locationtech.jts.geom.GeometryFactory geometryFactory =
            new org.locationtech.jts.geom.GeometryFactory(new PrecisionModel(), srid);

    WKTReader parser = new WKTReader(geometryFactory);

    if (wktString.startsWith(WKT_PREFIX)) {
        wktString = wktString.substring(WKT_PREFIX.length());
    }

    Geometry shape = null;
    try {
        shape = parser.read(wktString);
    } catch (org.locationtech.jts.io.ParseException e) {
        ConsoleManager.getInstance().exception(WKTConversion.class, e);
    }

    return shape;
}
 
Example #29
Source File: JtsAdapterIssue27Test.java    From mapbox-vector-tile-java with Apache License 2.0 5 votes vote down vote up
public static void testLineStringMisssingEndSegments() throws IOException, ParseException {
    final File wktFile = new File("src/test/resources/wkt/github_issue_27_01_multilinestring.wkt");
    final File outputFile = new File("linestring.mvt");
    final GeometryFactory gf = new GeometryFactory();
    final WKTReader reader = new WKTReader(gf);
    final MvtLayerParams mvtLayerParams = MvtLayerParams.DEFAULT;

    try(FileReader fileReader = new FileReader(wktFile)) {
        final Geometry wktGeom = reader.read(fileReader);
        final Envelope env = new Envelope(545014.05D, 545043.15D, 6867178.74D, 6867219.47D);
        final TileGeomResult tileGeom = JtsAdapter.createTileGeom(wktGeom, env, gf, mvtLayerParams, g -> true);

        final MvtLayerProps mvtLayerProps = new MvtLayerProps();
        final VectorTile.Tile.Builder tileBuilder = VectorTile.Tile.newBuilder();
        final VectorTile.Tile.Layer.Builder layerBuilder = MvtLayerBuild.newLayerBuilder("myLayerName", mvtLayerParams);
        final List<VectorTile.Tile.Feature> features = JtsAdapter.toFeatures(tileGeom.mvtGeoms, mvtLayerProps, new UserDataIgnoreConverter());
        layerBuilder.addAllFeatures(features);
        MvtLayerBuild.writeProps(layerBuilder, mvtLayerProps);
        tileBuilder.addLayers(layerBuilder);

        final VectorTile.Tile mvt = tileBuilder.build();
        try {
            Files.write(outputFile.toPath(), mvt.toByteArray());
        } catch (IOException e) {
            LoggerFactory.getLogger(JtsAdapterIssue27Test.class).error(e.getMessage(), e);
        }

        // Examine geometry output, will be a bit screwed but observe line segments are present
        final JtsMvt jtsMvt = MvtReader.loadMvt(outputFile, gf, new TagIgnoreConverter());
    }
}
 
Example #30
Source File: H2IndexingAbstractGeoSelfTest.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Check geo-index (dynamic).
 *
 * @param dynamic Whether index should be created dynamically.
 * @throws Exception If failed.
 */
@SuppressWarnings({"unchecked", "ConstantConditions"})
private void checkGeo(boolean dynamic) throws Exception {
    IgniteCache<Integer, EnemyCamp> cache = createCache("camp", true, Integer.class, EnemyCamp.class, dynamic);

    try {
        WKTReader r = new WKTReader();

        cache.getAndPut(0, new EnemyCamp(r.read("POINT(25 75)"), "A"));
        cache.getAndPut(1, new EnemyCamp(r.read("POINT(70 70)"), "B"));
        cache.getAndPut(2, new EnemyCamp(r.read("POINT(70 30)"), "C"));
        cache.getAndPut(3, new EnemyCamp(r.read("POINT(75 25)"), "D"));

        SqlQuery<Integer, EnemyCamp> qry = new SqlQuery(EnemyCamp.class, "coords && ?");

        Collection<Cache.Entry<Integer, EnemyCamp>> res = cache.query(
            qry.setArgs(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))"))).getAll();

        checkPoints(res, "A");

        res = cache.query(
            qry.setArgs(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))"))).getAll();

        checkPoints(res, "C", "D");

        // Move B to the first polygon.
        cache.getAndPut(1, new EnemyCamp(r.read("POINT(20 75)"), "B"));

        res = cache.query(
            qry.setArgs(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))"))).getAll();

        checkPoints(res, "A", "B");

        // Move B to the second polygon.
        cache.getAndPut(1, new EnemyCamp(r.read("POINT(30 30)"), "B"));

        res = cache.query(
            qry.setArgs(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))"))).getAll();

        checkPoints(res, "B", "C", "D");

        // Remove B.
        cache.getAndRemove(1);

        res = cache.query(
            qry.setArgs(r.read("POLYGON((5 70, 5 80, 30 80, 30 70, 5 70))"))).getAll();

        checkPoints(res, "A");

        res = cache.query(
            qry.setArgs(r.read("POLYGON((10 5, 10 35, 70 30, 75 25, 10 5))"))).getAll();

        checkPoints(res, "C", "D");

        // Check explain request.
        String plan = cache.query(new SqlFieldsQuery("explain select * from EnemyCamp " +
            "where coords && 'POINT(25 75)'")).getAll().get(0).get(0).toString().toLowerCase();

        assertTrue("__ explain: " + plan, plan.contains("coords_idx"));

        if (dynamic)
            cache.query(new SqlFieldsQuery("DROP INDEX \"EnemyCamp_coords_idx\"")).getAll();
    }
    finally {
        destroy(cache, grid(0), dynamic);
    }
}