laravel排序最近坐标



我有一个MySQL表,其中包含餐馆列表及其latitudes and longitudes。我想把数据按最近坐标排序发回。我正在调用API传递用户纬度和经度数据,我希望用户获得附近的餐馆。

p。我是laravel的新手,我还没有开发应用程序,只是维护应用程序。

<?php
namespace AppCentralLogics;
use AppModelsRestaurant;
use AppModelsOrderTransaction;
class RestaurantLogic
{
public static function get_restaurants($zone_id, $filter, $limit = 10, $offset = 1, $type='all')
{
$paginator = Restaurant::
withOpen()
->with(['discount'=>function($q){
return $q->validate();
}])->whereIn('zone_id', $zone_id)
->when($filter=='delivery', function($q){
return $q->delivery();
})
->when($filter=='take_away', function($q){
return $q->takeaway();
})
->Active()
->type($type)
->orderBy('open', 'desc')
->paginate($limit, ['*'], 'page', $offset);
/*$paginator->count();*/
return [
'total_size' => $paginator->total(),
'limit' => $limit,
'offset' => $offset,
'restaurants' => $paginator->items()
];
}
}

我不知道最好的旅行方式。但是我想给出一种方法来从一些latitudes and longitudes数据中获得您的位置数据。

即计算和latitudes and longitudes数。你可以判断这些数据是否接近。

例子。

你的位置是

$yourLocation = [ // sum 200
"userId" => 1,
"locationName" => "london d.street",
"latitudes" => 100,
"longitudes" => 100,
];

和一些数据

$someData = [
[ // sum 210
"locationId" => 1,
"locationName" => "restaurantA",
"latitudes" => 125,
"longitudes" => 85,
],
[ // 193
"locationId" => 2,
"locationName" => "restaurantB",
"latitudes" => 100,
"longitudes" => 93,
],
[ // 233
"locationId" => 3,
"locationName" => "restaurantC",
"latitudes" => 73,
"longitudes" => 160,
]
];

那么,如果您的位置总数接近目标位置总数,则结果将接近餐厅位置。是这样的:如果您的位置总数为200,您期望的餐厅列表排序为restaurantB ->馆→restaurantC .

$yourLocationSumPosition = data_get($yourLocation,'latitudes') + data_get($yourLocation,'longitudes');
// dd($yourLocationSumPosition); // 200
$result = collect($someData)->map(function($item) use($yourLocationSumPosition){
$sumPosition = data_get($item,'latitudes') + data_get($item,'longitudes');
return collect($item)->merge(["diff" => abs($yourLocationSumPosition - $sumPosition)])->toArray();
})->sortBy('diff')->toArray();
dd($result);

结果

array:3 [
1 => array:5 [
"locationId" => 2
"locationName" => "restaurantB"
"latitudes" => 100
"longitudes" => 93
"diff" => 7
]
0 => array:5 [
"locationId" => 1
"locationName" => "restaurantA"
"latitudes" => 125
"longitudes" => 85
"diff" => 10
]
2 => array:5 [
"locationId" => 3
"locationName" => "restaurantC"
"latitudes" => 73
"longitudes" => 160
"diff" => 33
]

diff正在管理排序条件。laravel提供了一些有用的方法,如collect()sortBy()等。您可以在这里查询。https://readouble.com/laravel/8.x/ja/collections.html method-sortby

试试。

最新更新