Hello there,
Are you looking for a way to find the nearest location using latitude and longitude in Laravel 10? If yes, then you are in the right place.
In this tutorial, I will guide you through the steps to find the nearest location in Laravel 10 using latitude and longitude.
Let’s get started.
Table of Contents
Step 1: Install Laravel
The first step is to install Laravel 10. You can do this by opening your terminal or command prompt and running the following command:
composer create-project laravel/laravel blog
This command will create a new Laravel project called “blog” in the current directory.
Step 2: Create a Route
The next step is to create a route for getting near locations from latitude and longitude. You can do this by adding the following code to your routes/web.php
file:
Route::get('find-places', [LocationController::class, 'index']);
This route will be handled by the index
method of the LocationController
.
Step 3: Create a Controller
The next step is to create a LocationController
and add the following code to it:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\User;
class LocationController extends Controller
{
public function index(Request $request)
{
$lat = YOUR_CURRENT_LATITUDE;
$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);
}
}
This controller will get the current latitude and longitude, and then find the nearest locations from the User
model. It uses the Haversine formula to calculate the distance between two points on the earth’s surface.
Step 4: Run the Laravel App
The final step is to run the Laravel app using the following command:
After running this command, you can go to your web browser and type the URL http://localhost:8000/find-places
to see the nearest locations based on your current latitude and longitude.
That’s it! You have successfully learned how to find the nearest location using latitude and longitude in Laravel 10.