gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 06:35:19 26 4
gpt4 key购买 nike

我正在开发一个 Laravel 应用程序,我需要在其中找到用户坐标一定半径范围内的所有产品。产品与用户是一对多的关系,用户可以拥有多个产品。我发现 haversine 算法可以计算两点之间的距离,但我似乎无法让它工作。

我有以下查询。

Controller

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

最佳答案

这是我的实现。我选择提前为我的查询设置别名,这样我就可以利用 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 替换为您希望在 $location 周围找到的模型$radius

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

希望这对您有所帮助。

关于php - Laravel中两点之间的Haversine距离计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37876166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com