PostgreSQL latitude longitude query PostgreSQL latitude longitude query postgresql postgresql

PostgreSQL latitude longitude query


Here's another example using the point operator:

Initial setup (only need to run once):

create extension cube;create extension earthdistance;

And then the query:

select (point(-0.1277,51.5073) <@> point(-74.006,40.7144)) as distance;     distance     ------------------ 3461.10547602474(1 row)

Note that points are created with LONGITUDE FIRST. Per the documentation:

Points are taken as (longitude, latitude) and not vice versa because longitude is closer to the intuitive idea of x-axis and latitude to y-axis.

Which is terrible design... but that's the way it is.

Your output will be in miles.

Gives the distance in statute miles between two points on the Earth's surface.


This module is optional and is not installed in the default PostgreSQL instalatlion. You must install it from the contrib directory.

You can use the following function to calculate the approximate distance between coordinates (in miles):

 CREATE OR REPLACE FUNCTION distance(lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT) RETURNS FLOAT AS $$DECLARE                                                       x float = 69.1 * (lat2 - lat1);                               y float = 69.1 * (lon2 - lon1) * cos(lat1 / 57.3);        BEGIN                                                         RETURN sqrt(x * x + y * y);                               END  $$ LANGUAGE plpgsql;


Assuming you've installed the earthdistance module correctly, this will give you the distance in miles between two cities. This method uses the simpler point-based earth distances. Note that the arguments to point() are first longitude, then latitude.

create table lat_lon (  city varchar(50) primary key,  lat float8 not null,  lon float8 not null);insert into lat_lon values('London, GB', 51.67234320, 0.14787970),('New York, NY', 40.91524130, -73.7002720);select   (  (select point(lon,lat) from lat_lon where city = 'London, GB') <@>  (select point(lon,lat) from lat_lon where city = 'New York, NY')  ) as distance_milesdistance_miles--3447.58672105301