How to configure PostgreSQL with Postgis to calculate distances

时间秒杀一切 提交于 2020-07-10 01:56:34

问题


I know that it might be dumb question, but I'm searching for some time and can't find proper answer. I have PostgreSQL database with PostGIS installed. In one table I have entries with lon lat (let's assume that columns are place, lon, lat).

What should I add to this table or/and what procedure I can use, to be able to count distance between those places in meters.

I've read that it is necessary to know SRID of a place to be able to count distance. Is it possible to not know/use it and still be able to count distance in meters basing only on lon lat?


回答1:


Short answer:

Just convert your x,y values on the fly using ST_MakePoint (mind the overhead!) and calculate the distance from a given point, the default SRS will be WGS84:

SELECT ST_Distance(ST_MakePoint(lon,lat)::GEOGRAPHY,
                   ST_MakePoint(23.73,37.99)::GEOGRAPHY) FROM places;

Using GEOGRAPHY you will get the result in meters, while using GEOMETRY will give it in degrees. Of course, knowing the SRS of coordinate pairs is imperative for calculating distances, but if you have control of the data quality and the coordinates are consistent (in this case, omitting the SRS), there is not much to worry about. It will start getting tricky if you're planing to perform operations using external data, from which you're also unaware of the SRS and it might differ from yours.

Long answer:

Well, if you're using PostGIS you shouldn't be using x,y in separated columns in the first place. You can easily add a geometry / geography column doing something like this.

This is your table ...

CREATE TABLE places (place TEXT, lon NUMERIC, lat NUMERIC);

Containing the following data ..

INSERT INTO places VALUES ('Budva',18.84,42.92),
                          ('Ohrid',20.80,41.14);

Here is how you add a geography type column:

ALTER TABLE places ADD COLUMN geo GEOGRAPHY;

Once your column is added, this is how you convert your coordinates to geography / geometry and update your table:

UPDATE places SET geo = ST_MakePoint(lon,lat);

To compute the distance you just need to use the function ST_Distance, as follows (distance in meters):

SELECT ST_Distance(geo,ST_MakePoint(23.73,37.99)) FROM places;

   st_distance   
-----------------
 686560.16822422
 430876.07368955
(2 Zeilen)

If you have your location parameter in WKT, you can also use:

SELECT ST_Distance(geo,'POINT(23.73 37.99)') FROM places;
   st_distance   
-----------------
 686560.16822422
 430876.07368955
(2 Zeilen)


来源:https://stackoverflow.com/questions/52445534/how-to-configure-postgresql-with-postgis-to-calculate-distances

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!