Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows with latitude-longitude values inside 10km radius?

Tags:

mysql

I have a site which shows posts from a certain city. I was thinking of changing from Cities to a radius around the user's location (10km in this case).

I don't know how to query using a radius. I can only think of doing a query with two conditions and get a square. e.g:

SELECT fields
FROM points
WHERE lat BETWEEN LAT1 AND LAT2
AND lon BETWEEN LON1 AND LON2

Is it possible to select rows inside a radius of X km/mi from a certain location?

like image 844
lisovaccaro Avatar asked Dec 07 '25 12:12

lisovaccaro


1 Answers

In general, you can use a WHERE query on any condition. So, supposing you have a function distance() that can compute the distance between two geographic points, you could do:

SELECT fields
FROM points
WHERE distance(lat, lon, city_lat, city_lon) <= 10

where city_lat and city_lon is the location of the city centre.

PostgreSQL contains a add-on function called earthdistance() that would help.

like image 141
Greg Hewgill Avatar answered Dec 09 '25 14:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!