Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to search all the location for given distance and given latitude and longitude in laravel

This is my senario: I saved shop details in mysql database in following way.

shopName, latitude, longitude,

now if someone gives his location in latitude and longitude with a distance (like 5km) I needs to filler all the shops within 5km to him,

in here user is the center and radius is 5km and I need to find all the shop within that circle, my application is developed in laravel 5.1

I tried to follow this code, but it wouldn't work.

can anyone help me.

like image 314
roledene JKS Avatar asked Dec 06 '25 08:12

roledene JKS


1 Answers

You can add the following code in your model

public function ScopeDistance($query,$from_latitude,$from_longitude,$distance)
{
  // 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('.$from_latitude.') ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians('.$from_longitude.') ) + sin( radians('.$from_latitude.') ) * sin( radians( latitude ) ) ) ) ) AS distance');
  return $query->select('*')->addSelect($raw)->orderBy( 'distance', 'ASC' )->groupBy('distance')->having('distance', '<=', $distance);
}

And you can use it with something like this

$ads = Ad::with(['user','photos'])->distance($from_latitude,$from_longitude,$distance)->get();
like image 61
St0iK Avatar answered Dec 08 '25 22:12

St0iK