[postgis-users] New to PostGIS - Simple Question

Stephen Woodbridge woodbri at swoodbridge.com
Thu May 26 11:48:18 PDT 2011


On 5/26/2011 2:30 PM, SixDegrees wrote:
>
> I'm quite new to GIS in general and PostGIS/Postgres in particular. I have to
> write a C/C++ routine to dredge values out of an existing PostGIS-enabled
> database. For the most part, this seems straightforward, but I can't figure
> out how to access the members of types stored as points.
>
> I'm aware of the ST_X() and ST_Y() SQL functions, but it using these seems
> to require two queries. Is it possible to extract the point type into a
> C/C++ struct/class with one call to the DB and process the results, or do I
> have to make two calls for each point? I can't seem to find a PostGIS API;
> does such a thing exist?
>
> A short example would be much appreciated, if possible.
>
> Thank you.

How about something like (untested):

#include <libpq-fe.h>

int main(int argc, char **argv)
{
PGconn *dbH;
char *sql;
int res;
char *dbconnect = "host=localhost user=postgres dbname=mydatabase";

dbH = PQconnectdb(dbconnect);
if (PQstatus(dbH) != CONNECTION_OK) {
   //die with message
}

sql = "select st_x(the_geom), st_y(the_geom) from points";
res = PQexec(dbH, sql);
if (PQresultStatus(res) != PGRES_TUPLES_OK) {
   // message no tuples
}
else {
   nRows = PQntuples(res);
   for (i=0; i<nRows; i++) {
     x = strtod(PQgetvalue(res, i, 0), NULL);
     y = strtod(PQgetvalue(res, i, 1), NULL);
     // do something with x, y
   }
}
PQclear(res);
PQfinish(dbH);

return 0;
}

-Steve



More information about the postgis-users mailing list