การหล่อ LineString เป็น Polygon จะส่งผลให้ ClassCastException เมื่อพิกัด y เหมือนกัน
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();
ผลลัพธ์รหัสดังกล่าวกับ ClassCastException () อย่างไรก็ตามเมื่อฉันเปลี่ยนค่า y ของพิกัดใด ๆ เช่นค่าแรกเป็น 34.6309 4ฉันไม่ได้รับข้อผิดพลาดใด ๆ
ฉันใช้org.locationtech.jts-1.17
.
สิ่งที่ฉันต้องการบรรลุคือการส่งเป็นรูปหลายเหลี่ยมโดยไม่มีข้อยกเว้นนี้ หรือข้อยกเว้นนั้นใช้ได้จริงและฉันไม่สามารถส่ง LineString สองพิกัดเป็นรูปหลายเหลี่ยมได้?
คำตอบ
เนื่องจาก MultiLineString ของคุณเป็นเส้นแนวตั้ง JTS ให้เส้นหลังเมื่อคุณขอซองจดหมาย (คิดว่านี่เป็นประโยชน์) ดังนั้นคุณต้องขอสิ่งinternalEnvelope
ที่จะให้Envelope
(xmin / xmax, ymin / ymax) จากนั้นคุณสามารถแปลงนี้ในPolygon
การใช้ระดับยูทิลิตี้org.geotools.geometry.jts.JTS
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();
System.out.println(envelope);
Envelope env = newGeom.getEnvelopeInternal();
System.out.println(env);
Polygon polygon = JTS.toGeometry(env);
System.out.println(polygon);
ซึ่งผลิต:
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))
หมายเหตุ: รูปหลายเหลี่ยมจะยังคงมีลักษณะเป็นเส้นเหมือนไม่มีความกว้าง แต่ฉันเดาว่านั่นคือสิ่งที่คุณต้องการ