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

前端之家收集整理的这篇文章主要介绍了php – 如何在laravel中搜索给定距离和给定纬度和经度的所有位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是我的晚会:
我通过以下方式在 mysql数据库中保存了商店详细信息.

shopName,latitude,longitude,

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

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

我试图遵循这个code,但它不会起作用.

谁能帮我.

解决方法

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

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);
}

你可以用这样的东西

$ads = Ad::with(['user','photos'])->distance($from_latitude,$distance)->get();

猜你在找的Laravel相关文章