Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Find the Nearest Location using Latitude & Longitude Tutorial

Last Updated on May 25, 2024 by

To calculate the geographical distance you have to use latitude and longitude which will help you to get the nearest location based on the current location of the user.

Let’s start to create application in laravel to get nearest location using latitude and longitude:

Step 1: Create Controller

Create a controller to handle the nearest location find:

php artisan make:controller LocationController

Implement method in app/Http/Controllers/LocationController.php file that helps to calculate the Nearest Location by lat and long:

// app/Http/Controllers/LocationController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LocationController extends Controller
{
    public function findNearest(Request $request)
    {
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');

        $nearestLocation = DB::table('locations')
            ->selectRaw("id, name, latitude, longitude, 
                ( 6371 * acos( cos( radians(?) ) *
                cos( radians( latitude ) )
                * cos( radians( longitude ) - radians(?)
                ) + sin( radians(?) ) *
                sin( radians( latitude ) ) )
                ) AS distance", [$latitude, $longitude, $latitude])
            ->orderBy('distance')
            ->first();

        return response()->json($nearestLocation);
    }
}

Step 2: Set Up Routes

Add a route to handle the nearest location request:

// routes/web.php

use App\Http\Controllers\LocationController;

Route::get('/find-nearest', [LocationController::class, 'findNearest']);

Step 3: Test Application

Start the Laravel development server:

php artisan serve

Open browser and type the following url in it:

http://localhost:8000/find-nearest?latitude=40.730610&longitude=-73.935242

Leave a Comment