How to configure PostgreSQL with Postgis to calculate distances

前端 未结 1 1942
野趣味
野趣味 2021-01-24 13:25

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 ent

相关标签:
1条回答
  • 2021-01-24 13:54

    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)
    
    0 讨论(0)
提交回复
热议问题