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
In this step, we'll install the laravel 11 application using the following command.
composer create-project laravel/laravel laravel-11-applicaton
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']);
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.
Now, run the laravel 11 application using the following command.
php artisan serve
You might also like: