获取用户从纬度到经度的距离

bgibtngc  于 2021-06-20  发布在  Mysql
关注(0)|答案(0)|浏览(233)

首先我想向您展示当前的数据库结构。有两个表:
用户
身份证件
名称
位置\u id
位置
身份证件
城市
拉丁美洲
液化天然气
现在我想实现一个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"

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题