zetcpw
Last Updated: February 25, 2016
·
2.376K
· st0ik
Jstoikidis gmail.com e0b88777

Calculating distance between two points (Latitude, Longitude)

Lets say that you have a table with stores ( fast foods, restaurants ) that offer their services ( food delivery ) in a certain distance from where they are located and you want to get all stores serving based on a specific location ( *ex users current location *).

You can accomplish this with the following SQL statement.

$lat = 41.118491 // user's latitude
$lng = 25.404509 // user's longitude

SELECT *, 
( 6371 * acos( cos( radians($lat) ) 
* cos( radians( latitude ) ) 
* cos( radians( longitude ) - radians($lng) ) + sin( radians($lat) ) 
* sin( radians( latitude ) ) ) ) 
AS calculated_distance 
FROM settings as T 
HAVING calculated_distance <= (SELECT distance FROM settings WHERE sid=T.sid) 
ORDER BY distance_calc

To search by miles instead of kilometers, replace 6371 with 3959.

Say Thanks
Respond

1 Response
Add your response

11573
0 fxkumyqlpb162vaifjv1mjqxp ne29oidrk1mjkjul8s1td  mn8cgrcgmqv7a0fayqtnsnsvevd

Anyone has an idea, how to make this with Laravel 4 framework ?

over 1 year ago ·