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.
Written by St0iK
Related protips
1 Response
Anyone has an idea, how to make this with Laravel 4 framework ?
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Mysql
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#