How to Find Nearest Location Using Latitude and Longitude in Laravel

Hello artisan,

In this tutorial, we will learn how to find or get the nearest location by using latitude and longitude in Laravel 9 application. If you don't know how to find how to find or get the nearest location by using latitude and longitude then this example is for you.

If you have latitude and longitude for locations then you can easily find them nearby you. I will give you a simple example of how to find the nearest location using latitude and longitude in Laravel.

I will add lat and long on the user's table to find users by the nearest latitude and longitude in Laravel applications.



Step 1: Install Laravel

First of all, we need to get a fresh Laravel version application using bellow command, So open your terminal OR command prompt and run the below command:

composer create-project laravel/laravel blog


Step 2: Create Route

In this step, we need to create one route for getting near a location from lat and long example.


use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LocationController;
| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
Route::get('near-by-places', [LocationController::class, 'index']);


Read also: Laravel 9 Scout Full Text Search Example with Database Driver


Step 3: Create Controller

In this step, we will create a controller and implement our logic. So create it like below:


namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Model\User;
class LocationController extends Controller
     * Display a listing of the resource.
     * @return \Illuminate\Http\Response
    public function index(Request $request)
        $users = User::select(""
                        ,DB::raw("6371 * acos(cos(radians(" . $lat . ")) 
                        * cos(radians( 
                        * cos(radians(users.lon) - radians(" . $lon . ")) 
                        + sin(radians(" .$lat. ")) 
                        * sin(radians( AS distance"))


Read also: How to Get Current User Location in Laravel


Now you can test by visiting the URL:




Hope it can help you.


Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js