Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading points from a Geography Polygon in a PostGIS database

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.

like image 285
Steph Avatar asked Jul 08 '11 23:07

Steph


2 Answers

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.

like image 78
Steph Avatar answered Oct 16 '22 10:10

Steph


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));
    }
like image 42
Shalom Crown Avatar answered Oct 16 '22 10:10

Shalom Crown