Find Nearest Location Using Latitude & Longitude In Laravel

Sometimes we need to find the nearest location of a user using latitude and longitude. So I am here to show you the source code of how to find the nearest location using latitude and longitude in PHP Laravel. 

So from this tutorial, you will learn how to find nearest location using latitude and longitude in Laravel 8 application. So let's see the example of how to find nearest location using latitude and longitude using sql in Laravel application:

app/controllers/LocationController.php

namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
use DB;
 
class LocationController extends Controller
{
    
    public function index(Request $request) {
 
        $lat = YOUR_LATTITUDE;
        $lon = YOUR_LONGITUDE;
            
        $data = DB::table("users")
            ->select("users.id"
                ,DB::raw("6371 * acos(cos(radians(" . $lat . ")) 
                * cos(radians(users.lat)) 
                * cos(radians(users.lon) - radians(" . $lon . ")) 
                + sin(radians(" .$lat. ")) 
                * sin(radians(users.lat))) AS distance"))
                ->groupBy("users.id")
                ->get();
 
      dd($data);
    }
}

 

Read also: Upload Large CSV File using Queue Job Batching in Laravel

 

Hope it can help you to find your latitude and longitude.

 

#laravel #laravel-8x