简体   繁体   中英

Taking coords from Google Maps and inserting it in PostgreSQL

My question is pretty basic. I am using Android Google Maps to take the coordinates off a location on the map and I want to insert it into a PostgreSQL database. I know I have to use PostGIS but how can I do that? Who can point me in the right direction?

My insertion query in Java looks like:

String query = "INSERT INTO modul (denumire, adresa, tip_retea, geom, poza)";
query += " VALUES ('" 
     + getset.getDenumire() + "', '" 
     + getset.getAdresa() + "', '"
     + getset.getTipretea()+ "', 
     ST_PointFromText('point(" + point.getX() + " " + point.getY()+ ")', 1), '" 
     + getset.getImagine() + "');";

Which generates me the following query:

INSERT INTO modul (denumire, adresa, tip_retea, geom, poza) VALUES ('', '', '', ST_PointFromText('point(23.78977 44.320948)', 1), 'irrelevant b64 encoded image');

But how can I properly insert the coordinates into a database? What datatype does the column 'geom' need to be? Thank you in advance.

As Igor has pointed out in the comments, your approach of concatenating strings into SQL statements is open to SQL injection. You can avoid this by using prepared statements in Java.

//prepare a statement -- omitting the non geometry values from OP question for clarity
String sql = "Insert into modul (geom) values (ST_MakePoint(?, ?))";
PreparedStatement stmt = conn.prepareStatement(sql);
//add the actual x and y values
stmt.setFloat(1, x);
stmt.setFloat(2, y);
stmt.executeUpdate();

Note you can use ST_MakePoint as an easier version of concatenating text values than using ST_PointFromText.

And, to answer the original question, the type should be geometry, though you can make this more explicit if you are only using a particular geometry type and you can also add a spatial reference ID (SRID), if you are working with one, which will act as a constraint on the column, eg,

CREATE table sometable (id serial, geom geometry(POINT, 4326));

will only allow you to insert points and in lat/lon. You can also set this to POLYGON , MUTLIPOLYGON , LINESTRING , etc. If you want to be more lax, you can just do,

 CREATE table sometable (id serial, geom geometry);

Yet another alternative is to use AddGeometryColumn which, again, allows to to explicitly state the geometry type and SRID, and also adds to the meta data view geometry_columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM