不是最理想的解决方案,但它应该有效:
public function getNearest()
{
$products= Product::orderBy('created_at','DESC')->paginate(5);
$user = Auth::user();
$address2 = $user->locatie; //location current user
$prepAddr2 = str_replace(' ','+',$address2);
$geocode2=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr2.'&sensor=false');
$output2= json_decode($geocode2);
$latitude2 = $output2->results[0]->geometry->location->lat;
$longitude2 = $output2->results[0]->geometry->location->lng;
$coordinate2 = new Coordinate($latitude2, $longitude2); //location user
$products->reject(function($product, $key) use($coordinate2) {
//function that calculate distance
$address = $product->locatie; //location of product
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$latitude = $output->results[0]->geometry->location->lat;
$longitude = $output->results[0]->geometry->location->lng;
$coordinate1 = new Coordinate($latitude, $longitude);
//location product
$calculator = new Vincenty();
$d = round($calculator->getDistance($coordinate1, $coordinate2) / 1000);
return $d > 10;
});
return view('welcome',compact('products'));
}
我之所以说它不是最优的,是因为你不能保证收到5个结果(分页不起作用)。这是因为您在php级别而不是数据库级别具有距离逻辑。解决这一问题的一种方法是计算产品的数量,以及它们是否<5、获取更多结果并计算距离,如果它们>5,取前5。
当然,最好的方法是在DB级别处理距离计算