I am new to PostGIS. I've got a table which contains boundaries of area in Polygon type. I would like to display the polygon on Google map. Each time, when google map view boundary is changed, the application should query PostGIS for any polygons in that map view. Can someone guide me to start?
2 Answers
Select * from Polygons where ST_Intersects(
ST_MakeBox2D(ST_MakePoint(lon1, lat1), ST_MakePoint(lon2, lat2)),
geom);
assuming that you have a table called Polygons and that your geometry field is called geom. You also need to make sure that you have a spatial index on the geometry field with:
Create index ix_spatial_geom on Polygons using gist (geom);
If you are planning on loading data from Postgis into google maps, have a look at the AS_GeoJSON function in Postgis, which allows you to create GeoJSON directly from Postgis, which you can then load into Google Maps directly, see this example: load GeoJSON in Google Maps
EDIT:
You can set the SRID when you import the data using the -s switch. It is highly advisable to explicitly set the SRID on a column either when you create the column or by running an update with UpdateGeometrySRID afterwards, as this helps with both enforcing integrity, and enable conversion from one coordinate system to another.
Once you have you data in a specified coordinate system, you can also use ST_Transfrom to convert from one coordinate system to another, on the fly, such as from 4326 to 3857 (the projected metres of Google Maps tiles).
ST_Intersects is probably the best solution for what you want.
If you are new to Postgis I recommend you to use their Postgis Cheat Sheet. This document has all Postgis's basic and most used commands that you will probably use for now and it helps you to get it quickly without having to read the whole manual.
How to use ST_Intersect and all most used alternatives is there.