Using PostGIS To Calculate Distance Between Two Points
One of the most common things you will want to do with geospatial data is calculate the distance between two points. Here is how you can do so with PostGIS.
Steps
Create our database.
Now connect to that database and add the postgis extension.
Create our points table for storing points we are interested in.
543797.01645757 Now look up some points. I used Google to find Woking and Edinburgh.
Now if we were to select the data, we would use:
id | name | location
----+-----------+-------------------
1 | Woking | (-0.56,51.3168)
2 | Edinburgh | (-3.1883,55.9533)
(2 rows)
Now to select distance, we can either make use of the ST_Distance_Sphere which is always uses the earth as a perfect sphere, which is quite fast, but slightly less accurate than using ST_DistanceSpheroid. I will list both:
ST_Distance_Sphere
Result: 543,797.01645757 meters.
ST_Distance_Spheroid
Result: 544,430.941199621 meters.
Checking
I wanted to see if these results lined up with others on the internet, which fortunately they do.
I am surprised the results are so different and awaiting clarifcation.
References
- Stack Overflow - Convert calculated latitude and longitude distance to metres/km
- Stack Overflow - Insert POINT into postgres database
First published: 16th August 2018