I have a geometry in java.lang.String format. I mean i take it directly from DB in as a java.lang.String which is stored in a variable. I want to convert it to jts Geometry type somehow. Is there any way to do it or what i'm trying to do is just a foolish approach?
Asked
Active
Viewed 9,638 times
2 Answers
10
I assume that your geometry has the WKT (Well Known Text) format. If not, you can get it in the WKT format by using the ST_AsText
method (requires spatial DB, which I assume you are using).
A simple example of how to get a geometry from a WKT String:
String wktString = "LINESTRING (0 0, 0 10)";
WKTReader reader = new WKTReader();
Geometry geom = reader.read(wktString);

Lars
- 2,315
- 2
- 24
- 29
-
Thank you. Which jar file do I need to import just to use WKTReader ? to work around this problem I'm calling a store procedure in PostgreSQL / PostGIS. I'm working in Grails 4 and Java 8. Thank you in advance for any response. – Juan Salvador Aug 06 '19 at 21:29
-
``
org.locationtech.jts jts-core 1.16.1
2
You will have to first convert from String to Coordinates before you can convert it to a Geometry.
If the values are comma separated you could split them and create an array of Coordinates
String[] split=stringgeometry.split(",");
Coordinate[] coordinates = new Coordinate[split.length/2];
index = 0;
for(int i=0;i<split.length;i+=2)
{
coordinates[index]=new Coordinate(split[i], split[i+1]);
index++;
}
After this you can create any Geometry that you want by using the GeometryFactory() class. For example to create a line string,
Geometry geometry = new GeometryFactory().createLineString(coordinates);
Is this what you want to do?

Mihai Iorga
- 39,330
- 16
- 106
- 107

Joyson
- 3,025
- 1
- 20
- 34