My goal: To read the points from a Geography Polygon stored in my PostGIS database.
The PostGIS manual has a great example of how to extract a Polygon from a database.
PGgeometry geom = (PGgeometry)r.getObject(1);
if (geom.getType() == Geometry.POLYGON ) {
Polygon pl = (Polygon)geom.getGeometry();
for (int r = 0; r < pl.numRings(); r++) {
LinearRing rng = pl.getRing(r);
System.out.println("Ring: " + r);
for (int p = 0; p < rng.numPoints(); p++ ) {
Point pt = rng.getPoint(p);
System.out.println("Point: " + p);
System.out.println(pt.toString());
}
}
}
I am dealing with Geography, however, not Geometry, so this code does not quite work for me. If I try to extract a Polygon from my table, I get the following ClassCastException
:
org.postgresql.util.PGobject cannot be cast to org.postgis.PGgeometry
I've modified the first two lines to look like this, which works:
PGobject area = (PGobject)rs.getObject("area");
if (area.getType().compareTo("geography") == 0) {
...
}
My problem now is that I can't figure out how to modify the third line of the code sample to work for Geography. I probably shouldn't cast it to the Polygon
type, since that is for Geometry, but is there an equivalent for Geography? I know that Geography is only partially supported for a lot of stuff, so I'm not sure what I can or can't do here.
I ended up deciding to get the coordinates from Postgres using the ST_AsText() method, rather than extracting them from some sort of Geography object in Java. Then I just parsed the polygon string in Java.
The PostgreSQL statement I executed looks like this:
SELECT id, name, ST_AsText(area) FROM area_table;
In Java I extract the String from the ResultSet after doing my JDBC query:
String area = rs.getString("ST_AsText");
And I get something that looks like this:
"POLYGON((-49 52,123 52,123 -4,-49 -4,-49 52))"
Then I just parsed the points out of that.
double[] bounds = new double[8];
int k = 0;
for (int i = 0; i < points.length; i++) {
String[] lonLat = points[i].split(" ");
for (int j = 0; j < lonLat.length; j++) {
bounds[k++] = Double.parseDouble(lonLat[j]);
}
}
I don't know if this is the best way to do it, but it's the best way I could figure out on my own.
If you know that the object is a polygon, it's quite simple.
PGpolygon polygon = (PGpolygon)rs.getObject("area");
for (int i = 0; i < polygon.points.length; i++)
{
System.out.println(String.format("(%d,%d)" polygon.points[i].x, polygon.points[i].y));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With