Laravel中两点之间的Haversine距离计算

11

我正在开发一个Laravel应用程序,需要查找用户坐标范围内的所有产品。产品与用户之间是一对多的关系,因此用户可以拥有多个产品。我已经发现了一种名为haversine算法的方法可以计算两点之间的距离,但我似乎无法让它起作用。

以下是我的查询代码。

控制器

$latitude = 51.0258761;
$longitude = 4.4775362;
$radius = 20000;

$products = Product::with('user')
->selectRaw("*,
            ( 6371 * acos( cos( radians(" . $latitude . ") ) *
            cos( radians(user.latitude) ) *
            cos( radians(user.longitude) - radians(" . $longitude . ") ) + 
            sin( radians(" . $latitude . ") ) *
            sin( radians(user.latitude) ) ) ) 
            AS distance")
->having("distance", "<", $radius)
->orderBy("distance")
->get();
我已将半径设置为20000以进行测试,并且所有产品的距离都为5687,问题似乎是产品的纬度和经度存储在用户表中,但我不确定如何在我的查询中访问它们。我尝试了user.latitude'user->latitude',但都没有起作用。

产品模型

class Product extends Model
{
    protected $fillable =
        [
            'soort',
            'hoeveelheid',
            'hoeveelheidSoort',
            'prijsPerStuk',
            'extra',
            'foto',
            'bio'
        ];

    public function User()
    {
        return $this->belongsTo('App\User');
    }

    public $timestamps = true;
}

用户模型

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword;

    protected $table = 'users';

    protected $fillable = 
        [
        'firstName', 
        'lastName', 
        'adres',
        'profilepic',
        'description', 
        'longitude',
        'latitude',
        'email', 
        'password'
    ];

    protected $hidden = ['password', 'remember_token'];

    public function product()
    {
        return $this->hasMany('App\Product');
    }
}
6个回答

27
这是我的实现方式。我选择提前将查询别名化,这样我就可以利用Pagination的优势。此外,您需要显式地选择要从查询中检索的列,并将它们添加到->select()中。例如users.latitude、users.longitude、products.name或任何其他列名。
我创建了一个类似于以下内容的范围:
public function scopeIsWithinMaxDistance($query, $location, $radius = 25) {

     $haversine = "(6371 * acos(cos(radians($location->latitude)) 
                     * cos(radians(model.latitude)) 
                     * cos(radians(model.longitude) 
                     - radians($location->longitude)) 
                     + sin(radians($location->latitude)) 
                     * sin(radians(model.latitude))))";
     return $query
        ->select() //pick the columns you want here.
        ->selectRaw("{$haversine} AS distance")
        ->whereRaw("{$haversine} < ?", [$radius]);
}

您可以将此范围应用于任何具有latitudelongitude的模型。

$location->latitude替换为您希望根据其搜索的latitude,并将$location->longitude替换为您希望根据其搜索的经度。

model.latitudemodel.longitude替换为您希望在$radius中定义的距离内找到的模型,这些模型基于$location周围的位置。

我知道您有一个运行良好的Haversine公式,但如果需要分页,就不能使用提供的代码。

希望这可以帮到您。


1
@Maxlight 这是针对千米的。如果是英里,你需要使用 3961 而不是 6371 - Ohgodwhy
@imrealashu 将它添加到 select() 中,我们将 {$haversine} 别名为 distance,这样你就可以 select('distance') - Ohgodwhy
我尝试过了,但是它说“distance”列不存在,所以没有起作用。然而,我在原始查询中有“distance”,所以甚至不需要将其添加到“select()”方法中。@Ohgodwhy - imrealashu
请注意:如果您遇到“distance is not available”或类似错误,则表示它在Postgres中无法正常工作。 - nutzt
@Ohgodwhy,我遇到了另一个问题,我收到了以下错误信息:: Undefined function: 7 ERROR: operator does not exist: bigint = character varying LINE 6: ...) AS distance from "addresses" where "users"."id" = "address... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts.我已经研究了大约一个小时,但似乎无法解决它。从看起来的情况来看,我正在对字符串和小数进行数学运算。但是不知道该如何解决。我尝试将用户的纬度和经度转换为十进制数,但没有效果。 - Tim Bogdanov
显示剩余9条评论

2
使用Haversine方法,您可以使用此函数计算两点之间的距离。它可以工作,但我不知道如何在Laravel中实现这一点。无论如何,想分享一下。
$lat1 //latitude of first point
$lon1 //longitude of first point 
$lat2 //latitude of second point
$lon2 //longitude of second point 
$unit- unit- km or mile

function point2point_distance($lat1, $lon1, $lat2, $lon2, $unit='K') 
    { 
        $theta = $lon1 - $lon2; 
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
        $dist = acos($dist); 
        $dist = rad2deg($dist); 
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);

        if ($unit == "K") 
        {
            return ($miles * 1.609344); 
        } 
        else if ($unit == "N") 
        {
        return ($miles * 0.8684);
        } 
        else 
        {
        return $miles;
      }
    }   

1
如果你愿意使用外部包,我建议使用非常有用的PHPGeo库。我在一个依赖这些精确计算的项目中使用过它,并且它完全正常工作。它可以帮助你避免从头开始编写计算,并经过测试以确保可行。

https://github.com/mjaschen/phpgeo

这是Harvesine的文档:https://phpgeo.marcusjaschen.de/#_distance_between_two_coordinates_haversine_formula。它涉及编程,可用于计算两个坐标之间的距离,您可以浏览以了解更多信息。

谢谢,但我使用的Haversine公式似乎不是问题所在。我只是无法弄清楚如何访问存储在产品所有者(用户)中而不是产品本身中的产品的纬度和经度。 - Robke22
完美!这证明对我的情况来说是一个简单而有效的解决方案。 :-) - ankush981

1

这是我正在使用的代码:

            $ownerLongitude = $request['longitude'];
            $ownerLatitude = $request['latitude'];
            $careType = 1;
            $distance = 3;

            $raw = DB::raw(' ( 6371 * acos( cos( radians(' . $ownerLatitude . ') ) * 
 cos( radians( latitude ) ) * cos( radians( longitude ) - radians(' . $ownerLongitude . ') ) + 
    sin( radians(' . $ownerLatitude . ') ) *
         sin( radians( latitude ) ) ) )  AS distance');
            $cares = DB::table('users')->select('*', $raw)
        ->addSelect($raw)->where('type', $careType)
        ->orderBy('distance', 'ASC')
        ->having('distance', '<=', $distance)->get();

非常好的解释。像魔法一样有效。 - Shalin Nipuna
乐意帮忙。 - K-Alex
对我来说很有效。谢谢! - undefined

0

我认为你需要的是查询构建器来建立连接。使用连接,你可以在查询中使用两个表的字段。目前你正在使用带有贪婪加载的关系,这将预先加载相关用户,但它们不能在SQL内部使用(Laravel实际上会执行2个查询)。

无论如何,我不会尝试在SQL中一步计算haversine公式,这可能不是真正的高效方式,并且查询可能变得难以维护。 这是我会做的事情:

  1. 计算具有纬度和经度的最小/最大包络,它应该比搜索半径稍大一些。
  2. 使用产品和用户的联接进行快速查询,只需检查用户位置是否在此包络内部即可。
  3. 对于结果列表的每个元素,使用PHP(而不是SQL)计算精确的haversine距离,删除超出半径的行,并相应地对列表进行排序。

0

我在Laravel中得到了一个解决方案。

    public function near($myLon, $myLat, $areaLon, $areaLat)
{
    $this->applyCriteria();
    $this->applyScope();

    $results = $this->model->select(DB::raw("SQRT(
        POW(69.1 * (latitude - " . $myLat . "), 2) +
        POW(69.1 * (" . $myLon . " - longitude) * COS(latitude / 57.3), 2)) AS distance, SQRT(
        POW(69.1 * (latitude - " . $areaLat . "), 2) +
        POW(69.1 * (" . $areaLon . " - longitude) * COS(latitude / 57.3), 2)) AS area"), "YOUR_TABLE.*")->get();

    $this->resetModel();
    $this->resetScope();

    return $this->parserResult($results);
}

答案以英里为单位,您需要将YOUR_TABLE替换为您的数据库表的名称。 谢谢,希望能有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接