Laravel 10 Search the Nearest Location with Latitude & Longitude

Last Updated on by in Laravel

Google has been the soul of our life. Google’s problem-solving approach has penetrated deep inside our lives. It offers tons of services that help us to smoothen our daily tasks.

Today, in this this essential guide will teach you how to find the nearest location in Laravel application using latitude and longitude.

We will show you how things are planned and put into action. Hence, we have mentioned the steps to help us find the nearest location in Laravel using location coordinates.

You must have a basic laravel application, a controller file, simple routes to request the controller, and a database connected to the laravel app. We will show you how to get the nearest location based on latitude and longitude in laravel.

How to Get the Nearest Location using Latitude and Longitude in Laravel 10

  • Step 1: Create Laravel Project
  • Step 2: Make Database Connection
  • Step 3: Generate Controller File
  • Step 4: Find Location with Latitude and Longitude
  • Step 5: Build Routes
  • Step 6: Start Application Server

Create Laravel Project

The first and foremost requirement is to have a blank Laravel project. To make the project ready, you must install and configure composer in your system.

Once the development machine is ready, go ahead and execute the given command.

composer create-project laravel/laravel --prefer-dist laravel-location-finder-example

Make Database Connection

Now the application is ready, the next primary task is to connect your database to the laravel app.

You have to look for the .env file; then, you need to define the database credentials in this file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=root
DB_PASSWORD=

If you are using MAMP local server in macOs; make sure to append UNIX_SOCKET and DB_SOCKET below database credentials in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

We have infused the database credentials in the .env file, and now the app is ready to be developed.

Generate Controller File

To write the logic to fetch the nearest location with lat and long requires a separate component.

Here is the command you can execute from the console to generate the controller.

php artisan make:controller FindLocationController

Find Location with Latitude and Longitude

We have to use the DB module to write the query to retrieve the results from the database.

Make sure to add the code to the app/Http/Controllers/FindLocationController.php file.

<?php
 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
 
class FindLocationController extends Controller
{
    public function index(Request $request) {
 
        $latitude = LATTITUDE_GOES_HERE;
        $longtitude = LONGITUDE_GOES_HERE;
            
        $showResult = DB::table("users")
            ->select("users.id"
                ,DB::raw("55555 * acos(cos(radians(" . $latitude . ")) 
                * cos(radians(users.lat)) 
                * cos(radians(users.lon) - radians(" . $longtitude . ")) 
                + sin(radians(" .$latitude. ")) 
                * sin(radians(users.lat))) AS distance"))
                ->groupBy("users.id")
                ->get();
 
      dd($showResult);
    }
}

Build Routes

Head over to the app/routes/web.php file and here in this file you have to create some routes that will communicate with the controller.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FindLocationController;

/*
|--------------------------------------------------------------------------
| 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-near-location', [FindLocationController::class, 'index']);

Start Application Server

Now everything has been set in its place. The final task is to run the application, invoke the command, and open the app on the browser.

php artisan serve
http://127.0.0.1:8000/find-near-location

Laravel Search the Nearest Location with Latitude & Longitude

Conclusion

The geographic coordinate system is a spherical or ellipsoidal coordinate system for calculating and communicating positions straight on the Earth as latitude and longitude.

It is the most straightforward, oldest, yet widely used of the various spatial reference systems that are in use.

In this guide, we learned what latitudes and longitudes are and how to use them to retrieve the nearest location in Laravel.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.