Laravel 11 Find Nearest Location By Latitude and Longitude

Hello, laravel web developers! In this article, we'll see laravel 11 find the nearest location by latitude and longitude. Here, we'll learn to get the nearest location using latitude and longitude in laravel 11. You can give latitude and longitude and find the location in laravel 11.

Sometimes, we need the user's location for the address to find the records based on the location.

How to Find Nearest Location in Laravel 11 using Latitude and Longitude

how to find nearest location in laravel 11

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-applicaton

 

Step 2: Define Route

Then, we'll define the routes in the web.php file.

routes/web.php

<?php
  
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('find-location', [LocationController::class, 'index']);
 
Step 3: Create Controller

Next, we'll create a controller and add the index function.

app/Http/Controllers/LocationController.php

<?php
  
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)
    {
        $lat = YOUR_CURRENT_LATTITUDE;
        $lon = YOUR_CURRENT_LONGITUDE;
           
        $users = User::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($users);
    }
}

Note: use 3,963 to get the distance in miles.
 

Step 4: Run the Laravel 11 Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS