To get the nearest area from a set of latitude and longitude coordinates in Laravel, we can use the haversine
formula to calculate the distance between the coordinates and a set of known coordinates for the area. The haversine
formula calculates the distance between two points on a sphere based on their latitude and longitude coordinates.
Here is an example of how we can use the haversine
formula to get the nearest area from a set of latitude and longitude coordinates in Laravel:
We have table name called areas where all our areas are stored. Also, we are going to going to use DB facade.
// Import the haversine formula
use Illuminate\Support\Facades\DB;
// Get the latitude and longitude coordinates
$lat = $request->input('lat');
$lng = $request->input('lng');
// Set the Max distance to get the areas from
$max_distance = 50;
// Formula
// This will calculate the distance in km
// if you want in miles use 3959 instead of 6371
$raw = \DB::raw('ROUND ( ( 6371 * acos( cos( radians('.$lat.') ) * cos( radians( areas.lat ) ) * cos( radians( areas.lng ) - radians('.$lng.') ) + sin( radians('.$lat.') ) * sin( radians( areas.lat ) ) ) ) ) AS distance');
// Return the nearest area
return $query->select(DB::raw($raw))
->having( 'distance', '<', $max_distance )
->orderBy( 'distance', 'ASC' )
->get();