[GIS] PostGIS – Geometry or Geography find points within distance in meters

postgispostgresqlsrid

I have a requirement where I need to store lat/long coordinates for locations all around the world. I then need to query for those locations that are within a specified distance (in meters) from another location. These distances are usually within the 500-1000 meter range so I don't need crazy precision.

Following various examples I've found, I've been using SRID 4326 with my geometry column in a PostGIS database. The column simply holds lat/long coordinates.

The ST_DWithin method takes a distance in meters for geography types, but I don't know what the unit is for 4326. It doesn't seem to be meters with some queries that I tried. I'm assuming it's degrees.

I've read that for performing Spatial queries on small areas, it's best to use geometries since operations are quicker at the price of precision. How can I use these methods to provide meters for either ST_DWithin or ST_Distance?

Best Answer

The definition of SRID 4326 is in fact IN DEGREES. ALso as it says in the ST_DWithin page:

Returns true if the geometries are within the specified distance of one another. For geometry units are in those of spatial reference and For geography units are in meters and measurement is defaulted to use_spheroid=true (measure around spheroid),

Since you're are using the 4326 SRID, you can cast from geometry to geography and vice versa like this :

select st_distance(<geom_column>::geography) from myTable;

Most of the functions in postgis are overloaded, meaning, they return values and run a different procedure based on the input data type.

eg:

boolean ST_DWithin(geometry g1, geometry g2, double precision distance_of_srid);

boolean ST_DWithin(geography gg1, geography gg2, double precision distance_meters);

they have the same name, but the first function returns T/F based on units of the srid, and the second returns T/F based on meters.

If you plug into the function geog types, for its calculation, will take into account the curve of the earth so the algorithm 'costs' a bit more.

If you want to check how much more it costs, you can run for each query an EXPLAIN-ANALYSE