如何根据laravel中的距离计算纬度和经度

时间:2016-07-09 10:34:22

标签: laravel

这是我的功能

public function getRshow(){

    $lats = $tenl[0]->latitude;
    $longs = $tlog[0]->longitude;
    $distance =$par_dis[0]->partner_distance; 
    $project = "SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( $lats - latitude) *  pi()/180 / 2), 2) +COS( $lats * pi()/180) * COS(latitude * pi()/180) * POWER(SIN((  $longs - longitude) * pi()/180 / 2), 2) ))) as distance  
    FROM `abserve_renterpost`  having  distance <= $distance order by distance";
    $la=DB::SELECT($project);

    $lara=array();
    foreach ($project as $key => $v) {
    $lara[]=(get_object_vars($v));
    }
}

如果我只运行查询,那么我的查询工作正常,但是如果我将查询转换为值和数组格式它不起作用,则错误显示如下。

(SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '  - latitude) * pi()/180 / 2), 2) +COS( 27.7   * pi()/180) * COS(latitude * ' at line 1 (SQL: SELECT * , (3956 * 2 * ASIN(SQRT( POWER(SIN(( 27.7   - latitude) * pi()/180 / 2), 2) +COS( 27.7   * pi()/180) * COS(latitude * pi()/180) * POWER(SIN(( 74.12399600000003
- longitude) * pi()/180 / 2), 2) ))) as distance 
FROM `abserve_renterpost` having distance <= 200 order by distance))

1 个答案:

答案 0 :(得分:1)

  • 我注意到$lats27.7这是奇怪的。

试试这个

$lats = $tenl[0]->latitude;
$longs = $tlog[0]->longitude;
$distance =$par_dis[0]->partner_distance;
$project = <<<SQL
    SELECT * , (3956 * 2 * ASIN(
      SQRT(
        POWER(SIN(($lats - `latitude`) *  pi() / 180 / 2), 2)
        + COS($lats * pi() / 180)
          * COS(`latitude` * pi() / 180)
          * POWER(SIN(($longs - `longitude`) * pi() / 180 / 2), 2)
      ))
      ) as 'distance'

    FROM `abserve_renterpost`
    WHERE distance <= $distance
    ORDER BY distance;
SQL;
$la=DB::select($project);

$lara=array();
foreach ($project as $key => $v) {
    $lara[]=(get_object_vars($v));
}