Find the nearest location using latitude and longitude in laravel | PHP
Hello buddy, how are you I hope you are doing fantastic, thanks for reaching out on our website, I bet this blog will definitely help you out to get the nearest location based on two latitudes and two longitude
You can use the mentioned code in your PHP or in the Laravel application as well, I know that you search over the internet, and at every places, they are finding out the nearest location by implementing the code in sql.
Will show you how to get the nearest location based on longitude and latitude by using the code on sql, or without writing sql code, by using just the plane PHP code.
Get nearest location by using PHP Code
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
return round($distance, 2);
The above value comes in the KM, the above code will give you the distance in KM between two latitude and longitude.
By implementing the logic in sql
$lat = YOUR_CURRENT_LATTITUDE;
$lon = YOUR_CURRENT_LONGITUDE;
$users = User::select("users.id"
,DB::raw("6371 * acos(cos(radians(" . $lat . "))
* cos(radians(users.lat))
* cos(radians(users.lon) - radians(" . $lon . "))
+ sin(radians(" .$lat. "))
* sin(radians(users.lat))) AS distance"))
->groupBy("users.id")
->get();
dd($users);
From the above way, you can also get the shortest distance between two latitude and longitude.
I hope now you understood how to get the shortest distance by using latitude and longitude, still facing issue feel free to comment.