Home > database >  Distance between two locations in Laravel using latitude and longitude in database query
Distance between two locations in Laravel using latitude and longitude in database query

Time:12-29

I have a table called warehouses, which has latitude & longitude columns. I am searching nearby warehouses from my current location (Providing latitude & longitude, radius) to find the warehouses nearby me in a given radius.

this operation needs to be performed by the query, not manual functions.

CodePudding user response:

Use This mysql Function : ST_Distance_Sphere

Supported since MySql 5.7 version and above.

select ST_Distance_Sphere(point(lon,lat), point(lon,lat))

CodePudding user response:

For those who might need it, I have solved this problem.

$lati = (float)$request->latitude;
$longt = (float)$request->longtitude;
$rad = (int)$request->radius;



$distance_result = "(6371 * acos(cos(radians($lati))
* cos(radians(latit))
* cos(radians(longt)
- radians($longt))
  sin(radians($lati))
* sin(radians(latit))))";


$warhouses = Warhouse::select('id', 'name')
    ->selectRaw("{$distance_result} AS distance")
    ->whereRaw("{$distance_result} < ?", [$rad])
    ->get();



return view('test')->with('nearbys', $warhouses);
  • Related