Add Distance Calculation
This commit is contained in:
@@ -4,6 +4,7 @@ namespace Modules\Linksehat\Http\Controllers\Api;
|
||||
|
||||
use App\Helpers\Helper;
|
||||
use App\Models\Organization;
|
||||
use DB;
|
||||
use Illuminate\Contracts\Support\Renderable;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
@@ -19,11 +20,45 @@ class HospitalController extends Controller
|
||||
{
|
||||
$hospitals = Organization::query()
|
||||
->with(['currentAddress'])
|
||||
->where('type', 'hospital')
|
||||
->where('organizations.type', 'hospital')
|
||||
->when($request->search ?? null, function($query, $search) {
|
||||
$query->where('name', 'LIKE', '%'.$search.'%');
|
||||
})
|
||||
->paginate(6);
|
||||
});
|
||||
if ($request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
|
||||
$hospitals->leftJoin('addresses', function($q) {
|
||||
$q->on('organizations.main_address_id', '=', 'addresses.id');
|
||||
$q->where('addresses.addressable_type', '=', Organization::class);
|
||||
});
|
||||
$hospitals->select([
|
||||
"organizations.*",
|
||||
DB::raw("ST_Distance_Sphere(point(addresses.lng,addresses.lat), point(".$request->lng.",".$request->lat.")) /1000 as distance_km")
|
||||
]);
|
||||
|
||||
$hospitals->orderBy('distance_km', 'desc');
|
||||
} else {
|
||||
$hospitals->orderBy('organizations.name', 'asc');
|
||||
}
|
||||
|
||||
// if ($request->has('order_by')) {
|
||||
// switch($request->order_by) {
|
||||
// case 'distance_asc':
|
||||
// if ($request->order_by == 'distance_asc' && $request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
|
||||
// $hospitals->orderBy('distance_km', 'asc');
|
||||
// break;
|
||||
// }
|
||||
// case 'distance_desc':
|
||||
// if ($request->order_by == 'distance_desc' && $request->has('lat') && !empty($request->lat) && $request->has('lng') && !empty($request->lng)) {
|
||||
// $hospitals->orderBy('distance_km', 'desc');
|
||||
// break;
|
||||
// }
|
||||
// default:
|
||||
// $hospitals->orderBy('organizations.name', 'asc');
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
|
||||
$hospitals = $hospitals->paginate($request->limit ?? 6);
|
||||
// dd($hospitals->toArray());
|
||||
|
||||
|
||||
return response()->json([
|
||||
|
||||
@@ -22,7 +22,7 @@ class HospitalResource extends JsonResource
|
||||
'address' => $this->currentAddress->text ?? null,
|
||||
'lat' => $this->currentAddress->lat ?? null,
|
||||
'lng' => $this->currentAddress->lng ?? null,
|
||||
'distance' => '200 m',
|
||||
'distance' => isset($this->distance_km) ? round($this->distance_km) . ' km' : '-',
|
||||
'city_name' => 'Kota Tangerang',
|
||||
'phone' => $this->meta->phone,
|
||||
'photo_url' => asset('images/default-hospital-image.png'),
|
||||
|
||||
Reference in New Issue
Block a user