1

There are two fields in the database table, latitude and longitude. (Other fields too, but they are not important now.)

I have a function, where are three parameters: latitude, longitude and max_distance (km).

Is there any way to construct raw PostgreSQL query that returns only the rows that represent location which is within that max_distance (km) measured from given latitude and longitude?

Example parameters latitude=59.9138699, longitude=10.7522451, max_distance=10

2

1 Answer 1

1

To do this, use postgis.

Postgis has functions such as ST_Distance and ST_PointFromText:

select * from tbl
where ST_Distance(
    ST_PointFromText('POINT(' || longitude || ' ' || latitude || ')', 4326), 
    ST_PointFromText('POINT(10.7522451 59.9138699)', 4326)
) < 10000;

To do this fast, you should use a geometry field and index it.


You should also learn a bit about spatial reference systems and SRID. SRID 4326 denotes the WGS84 coordinate system, commonly in use on the web.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.