Java Code Examples for org.locationtech.jts.io.WKTReader#read()

The following examples show how to use org.locationtech.jts.io.WKTReader#read() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 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: 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 12
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 13
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 14
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 15
Source File: CSVMappingGenerator.java    From GeoTriples with Apache License 2.0 4 votes vote down vote up
public void run() throws IOException {
	CsvReader reader = new CsvReader(new FileInputStream(pathToShapefile), Charset.defaultCharset());
	reader.setDelimiter(separator);
	reader.setSafetySwitch(false);

	reader.readHeaders();
	// Iterate the rows

	Path p = Paths.get(pathToShapefile);
	String tmp = p.getFileName().toString();
	String typeName = tmp.substring(0, tmp.lastIndexOf('.'));
	triplesMaps.put(typeName, "");
	triplesMaps.put(typeName, triplesMaps.get(typeName) + printTriplesMap(typeName));
	triplesMaps.put(typeName, triplesMaps.get(typeName) + printLogicalSource(typeName));
	triplesMaps.put(typeName, triplesMaps.get(typeName) + printSubjectMap(baseURI, typeName));

	boolean hasgeometry = false;
	String typeNameGeo = typeName + "_Geometry";
	WKTReader wktReader = new WKTReader();
	String geometry_identifier = null;
	boolean has_record = reader.readRecord();
	for (String header : reader.getHeaders()) {
		String identifier = header;
		if (identifier.equalsIgnoreCase("the_geom")) {
			geometry_identifier = identifier;
			hasgeometry = true;
			continue;
		}
		if (has_record) {
			try {
				if (wktReader.read(reader.get(identifier)) != null) {
					hasgeometry = true;
					geometry_identifier = identifier;
					continue;
				}
			} catch (ParseException e1) {
				System.err.println(reader.get(identifier));
			}
		}

		String datatype = TranslateDataTypeToXSD("String");
		triplesMaps.put(typeName,
				triplesMaps.get(typeName) + printPredicateObjectMap(identifier, identifier, datatype, typeName));

	}

	if (hasgeometry) {
		triplesMaps
				.put(typeName,
						triplesMaps.get(typeName) + printPredicateObjectMap(true, "hasGeometry",
								baseURI + (baseURI.endsWith("/") ? "" : "/") + typeName
										+ "/Geometry/{GeoTriplesID}",
								null, null, "ogc", null, typeName, true, false));
		triplesMaps.put(typeNameGeo, "");
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printTriplesMap(typeNameGeo));
		triplesMaps.put(typeNameGeo, triplesMaps.get(typeNameGeo) + printLogicalSource(typeName));
		triplesMaps.put(typeNameGeo,
				triplesMaps.get(typeNameGeo) + printSubjectMap(baseURI, typeName, "ogc", true));
		triplesMaps.put(typeNameGeo,
				triplesMaps.get(typeNameGeo) + printGEOPredicateObjectMaps(geometry_identifier));
	}
	printmapping();
	printontology();
}
 
Example 16
Source File: SpatialQueryExample.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param args Command line arguments, none required.
 */
public static void main(String[] args) throws Exception {
    // Starting Ignite node.
    try (Ignite ignite = Ignition.start("examples/config/example-ignite.xml")) {
        // Preparing the cache configuration.
        CacheConfiguration<Integer, MapPoint> cc = new CacheConfiguration<>(CACHE_NAME);

        // Setting the indexed types.
        cc.setIndexedTypes(Integer.class, MapPoint.class);

        // Starting the cache.
        try (IgniteCache<Integer, MapPoint> cache = ignite.createCache(cc)) {
            Random rnd = new Random();

            WKTReader r = new WKTReader();

            // Adding geometry points into the cache.
            for (int i = 0; i < 1000; i++) {
                int x = rnd.nextInt(10000);
                int y = rnd.nextInt(10000);

                Geometry geo = r.read("POINT(" + x + " " + y + ")");

                cache.put(i, new MapPoint(geo));
            }

            // Query to fetch the points that fit into a specific polygon.
            SqlQuery<Integer, MapPoint> query = new SqlQuery<>(MapPoint.class, "coords && ?");

            // Selecting points that fit into a specific polygon.
            for (int i = 0; i < 10; i++) {
                // Defining the next polygon boundaries.
                Geometry cond = r.read("POLYGON((0 0, 0 " + rnd.nextInt(10000) + ", " +
                    rnd.nextInt(10000) + " " + rnd.nextInt(10000) + ", " +
                    rnd.nextInt(10000) + " 0, 0 0))");

                // Executing the query.
                Collection<Cache.Entry<Integer, MapPoint>> entries = cache.query(query.setArgs(cond)).getAll();

                // Printing number of points that fit into the area defined by the polygon.
                System.out.println("Fetched points [cond=" + cond + ", cnt=" + entries.size() + ']');
            }
        }
    }
}
 
Example 17
Source File: GeometryValuesTest.java    From sldeditor with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Test method for {@link
 * com.sldeditor.rendertransformation.types.GeometryValues#GeometryValues()}.
 */
@Test
void testGeometryValues() {
    GeometryValues testObj = new GeometryValues();
    testObj.createInstance();

    assertEquals(
            Arrays.asList(
                    Geometry.class,
                    LineString.class,
                    Point.class,
                    Polygon.class,
                    GridCoverage2D.class),
            testObj.getType());

    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory();

    Geometry geometry = null;
    WKTReader reader = new WKTReader(geometryFactory);
    try {
        Point point = (Point) reader.read("POINT (1 1)");
        geometry = point;
    } catch (ParseException e) {
        e.printStackTrace();
        fail("");
    }

    testObj.setDefaultValue(geometry);
    String p = geometry.toString();
    assertEquals(testObj.getExpression().toString(), p);

    // Geometry value
    testObj.setValue(geometry);
    assertEquals(testObj.getExpression().toString(), p);

    // Literal expression
    Expression expectedExpression = ff.literal(p);
    testObj.setValue(expectedExpression);
    assertEquals(testObj.getExpression().toString(), p);

    // Attribute expression
    expectedExpression = ff.property("test");
    testObj.setValue(expectedExpression);
    assertEquals(expectedExpression, testObj.getExpression());

    // Not set
    testObj.setValue("");
    assertNull(testObj.getExpression());

    FieldConfigBase field =
            testObj.getField(
                    new FieldConfigCommonData(
                            GeometryValues.class,
                            FieldIdEnum.INITIAL_GAP,
                            "label",
                            true,
                            false,
                            false));
    assertEquals(FieldConfigGeometry.class, field.getClass());

    // Increase code coverage
    TestGeometryValues testObj2 = new TestGeometryValues();
    testObj2.populateSymbolType(null);
}
 
Example 18
Source File: JTSHelper.java    From arctic-sea with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a JTS Geometry from an WKT representation. Switches the
 * coordinate order if needed.
 *
 * @param wkt
 *            WKT representation of the geometry
 * @param srid
 *            the SRID of the newly created geometry
 *
 * @return JTS Geometry object
 *
 * @throws ParseException
 *             If an error occurs
 */
public static Geometry createGeometryFromWKT(String wkt, int srid) throws ParseException {
    WKTReader wktReader = getWKTReaderForSRID(srid);
    LOGGER.debug("FOI Geometry: {}", wkt);
    return wktReader.read(wkt);
}