Last Updated: September 09, 2019
·
7.792K
· Dimitris Stoikidis

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.

1 Response
Add your response

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

over 1 year ago ·