final WKTReader wktReader = new WKTReader();
String geomString = "MULTILINESTRING ((-98.753985 34.63093, -98.7555568 34.63093))";
MultiLineString geom = (MultiLineString)wktReader.read(geomString);
LineString newGeom = new GeometryFactory().createLineString(geom.getCoordinates());
Polygon envelope = (Polygon) newGeom.getEnvelope();

Such code results with ClassCastException(). However, when I'm changing y value of any of coordinates, e.g. first one to 34.63094, I don't get any error.
I am using org.locationtech.jts-1.17.

What would I like to achieve is to cast it to Polygon without this Exception. Or, the exception is actually valid and I shouldn't be able to cast any two-coordinate LineString to Polygon?

  • 2
    Three distinct vertex locations are required to construct a Polygon (which will have four vertices). WKT for a POLYGON requires all four vertices (first and last the same). – Vince Aug 17 '20 at 13:01

Because your MultiLineString is a vertical line JTS gives you back a line when you ask for the envelope (it thinks this is helpful). So you need to ask for the internalEnvelope which will give you an Envelope (an xmin/xmax, ymin/ymax). You can then convert this into a Polygon using the org.geotools.geometry.jts.JTS Utility class.

final WKTReader wktReader = new WKTReader();
String geomString = "MULTILINESTRING ((-98.753985 34.63093, -98.7555568 34.63093))";
MultiLineString geom = (MultiLineString) wktReader.read(geomString);
LineString newGeom = new GeometryFactory().createLineString(geom.getCoordinates());
Geometry envelope = newGeom.getEnvelope();
Envelope env = newGeom.getEnvelopeInternal();
Polygon polygon = JTS.toGeometry(env);

Which produces:

LINESTRING (-98.7555568 34.63093, -98.753985 34.63093)
Env[-98.7555568 : -98.753985, 34.63093 : 34.63093]
POLYGON ((-98.7555568 34.63093, -98.753985 34.63093, -98.753985 34.63093, -98.7555568 34.63093, -98.7555568 34.63093))

Note: the polygon will still look like a line as it has no width, but I guess that is what you want.

  • I've justed looked up this getEnvelope function and now I understand why last expression works for a line which is not vertical. It outputs envelope, that has four coordinates, while for vertical line it outputs Linestring with two points. I think that was missing in my thought process. And yes, this is what I want, cause I use Polygon type in further code. Thank you. – kujaw Aug 17 '20 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.