[postgis-users] Getting started with Java
Gustavo Henrique Sberze Ribas
gribas at cpqd.com.br
Mon Jul 25 10:05:31 PDT 2005
> > Hi,
> >
> > I'd like to start using postgis from Java.
> > I've been reading some material in the net but I still got some
> > questions:
> >
> > What is the best way to read and write Geometry objects?
To read you can use the PGgeometry object as described in the docs, Ex:
// get latitude/longitude from a Point geometry
PGgeometry geometry = (PGgeometry) resultSet.getObject("geom");
if (geometry.getGeoType() == Geometry.POINT) {
Point p = (Point) geometry.getGeometry();
reg.setLongitude(p.x);
reg.setLatitude(p.y);
} else {
reg.setLongitude(0f);
reg.setLatitude(0f);
}
To write you can use a preparededStatement:
Point p = new Point(-47.12, -22.374);
p.setSrid(4326);
PreparedStatement ps = conn.prepareStatement("INSERT INTO myTable(geom) VALUES(?)");
ps.setObject(1, new org.postgis.PGgeometry(p));
or this:
Point p = new Point(10,10);
p.setSrid(4774);
String sql = "INSERT INTO myTable(geom) VALUES('" + p.toString() +"')";
> > I need to perform some GIS calculation and so I guess I need JTS to do
> > that. I noticed that the opengis Java driver doesn't support JTS (it's
> > beta), so I found wkb4j which seems to do what I need. However, I'm
> > not sure how can I encode a JTS Geometry object to a wkb format for
> > writing new objects to postgis.
Markus was working on a wrapper to do just this. I believe you can get it
on the PostGIS CVS, under jdbc2. Below is an example that transforms JTS to
EWKT, you can then use this EWKT to send data to Postgres/PostGIS, but be
aware of precision issues:
public static String JTS2EWKT(com.vividsolutions.jts.geom.Polygon jtsPolygon) {
if (jtsPolygon.getSRID() <= 0) {
// enforce default SRID
return ("SRID="+DEFAULT_SRID+";"+jtsPolygon.toText());
} else {
// use Polygon's SRID
return ("SRID="+jtsPolygon.getSRID()+";"+jtsPolygon.toText());
}
}
--
Gustavo
More information about the postgis-users
mailing list