I have a table in my database named users
and I have created a model User
. Every user in my database has a certain latitude
and longitude
. So, I want to sort the users based on their location. An example of this would be: Let's say one of my user has latitude 34.567 and longitude 56.983. Now, I want to display all the users whose latitude and longitude is very near to that of mine. Let's say: 34.975 and 56.884. So, I want to display that particular users whose location is near to the location of my user. So, how do I do that sorting stuff in Laravel.
Note: Yes, there is no code with the question. But, I have searched in the documentation for something like this but, they have documentation for particular cases like
sorting on the basis of posted time and so on.
Thanks.
Fairly generic PHP code for sorting via distance:
// Get the requested latitude and longitude (from whatever source)
$lat = $coords['latitude'];
$lng = $coords['longitude'];
$distance = 81; // Radius of distance in kilometers
$earthRadius = 6731; // accepted mean radius of the Earth in kilometres
if ($distance == 0) {
$distance = 81; // Default to 50 miles (in km) if no distance given!
}
$latDistance = $distance / 111.325;
$lngDistance = (cos(abs($lat)) * $distance) / 111.325;
$minLat = $lat - $latDistance;
$maxLat = $lat + $latDistance;
$minLng = $lng - $lngDistance;
$maxLng = $lng + $lngDistance;
$boundaryCalculation = "(users.latitude >= {$minLat} AND users.latitude <= {$maxLat} AND users.longitude >= {$minLng} AND users.longitude <= {$maxLng})";
$distanceCalculation = "(ACOS(SIN({$lat}*PI()/180) * SIN(users.latitude*PI()/180) + (COS({$lat}*PI()/180)*COS(users.latitude*PI()/180) * COS((({$lng}-users.longitude)*PI()/180)))) * {$earthRadius})";
// Create the query
// Note, should be parameterized but this gives the idea
$query = "SELECT * FROM users WHERE " . $boundaryCalculation . " AND " . $distanceCalculation;
This gives a good introduction: https://www.scribd.com/presentation/2569355/Geo-Distance-Search-with-MySQL
Note that from version 5.7 MySQL provides a built-in function for calculating the distance between two points on a sphere. Might be of use!
https://dev.mysql.com/doc/refman/5.7/en/spatial-convenience-functions.html