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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With