获取用户与经纬度的距离

时间:2018-09-06 10:08:44

标签: mysql laravel eloquent geolocation

首先,我想向您展示当前的数据库结构。有两个表:

用户

  • id
  • 名称
  • location_id

位置

  • id
  • 城市
  • lat
  • lng

现在,我想实现一个API,该API可以获取附近的用户及其距离。像附近的用户一样:

{{name:user1,distance:5km},(name:user2,distance:7 km)}

这是我的位置模型:

public function scopeIsWithinMaxDistance($query, $rsine, $radius = 5)
{
  return $query->selectRaw("*,{$rsine} AS distance")
               ->whereRaw("{$rsine} < ?"[$radius])->orderBy('distance');
}

public static function rsine($coordinates)
{
    return '(6371 * acos(cos(radians(' . $coordinates['latitude'] . ')) 
    * cos(radians(`lat`)) 
    * cos(radians(`lng`) 
    - radians(' . $coordinates['longitude'] . ')) 
    + sin(radians(' . $coordinates['latitude'] . ')) 
    * sin(radians(`lat`))))';
}

public static function convertKMToMiles($dist)
{
    return $dist * 1.609344;
}

我的控制器:

   $coordinates = ['latitude' => '28.392200', 'longitude' => '77.320801'];

   $rsine = Location::rsine($coordinates);

   $radius = Location::convertKMToMiles(5);

   $users = User::with(['location' => function ($query) use ($rsine)
   {
      $query->selectRaw("*, {$rsine} AS distance");}])
            ->whereHas('location',function ($query) use ($radius, $rsine) 
           {$query->isWithinMaxDistance($rsine, $radius);})->get();

输出:语法错误

"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*,(6371 * acos(cos(radians(28.392200)) \n    * cos(radians(`lat`)) \n    * cos(rad' at line 1 (SQL: select * from `users` where exists (select *, *,(6371 * acos(cos(radians(28.392200)) \n    * cos(radians(`lat`)) \n    * cos(radians(`lng`) \n    - radians(77.320801)) \n    + sin(radians(28.392200)) \n    * sin(radians(`lat`)))) AS distance from `locations` where `users`.`location_id` = `locations`.`id` and (6371 * acos(cos(radians(28.392200)) \n    * cos(radians(`lat`)) \n    * cos(radians(`lng`) \n    - radians(77.320801)) \n    + sin(radians(28.392200)) \n    * sin(radians(`lat`)))) < 8.04672 order by `distance` asc) and `users`.`deleted_at` is null)",
    "exception": "Illuminate\\Database\\QueryException"

0 个答案:

没有答案