如何在laravel中搜索给定距离和给定纬度和经度的所有位置

rol*_*JKS 3 php mysql google-maps geolocation laravel-5.1

这是我的senario:我通过以下方式在mysql数据库中保存了商店详细信息.

shopName,纬度,经度,

现在,如果有人在经度和距离(如5公里)的位置给出了他的位置,我需要在距离他5公里范围内填写所有商店,

在这里用户是中心,半径是5公里,我需要找到该圈内的所有商店,我的应用程序是在laravel 5.1中开发的

我试图遵循这个代码,但它不起作用.

谁能帮我.

St0*_*0iK 11

您可以在模型中添加以下代码

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);
}
Run Code Online (Sandbox Code Playgroud)

你可以用这样的东西

$ads = Ad::with(['user','photos'])->distance($from_latitude,$from_longitude,$distance)->get();
Run Code Online (Sandbox Code Playgroud)