Laravel Calculate Distance Between Two Latitude and Longitude Example
Hey,
This example is focused on how to calculate distance between two latitude and longitude in laravel. In this article, we will implement a laravel calculate distance between two coordinates. I would like to show you calculate distance between two points in laravel. Iām going to show you about calculate distance between two coordinates laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.
Whenever you need to get nearest posts from lat and long and if you are working on laravel query builder. then you can get distance easily using DB::raw(), so you can learn from following example how to get nearest value from mysql laravel.
Example 1:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class ProductController extends Controller
{
/**
* Write code on Method
*
* @return response()
*/
public function index(Request $request)
{
$lat = 51.0258751;
$lon = 4.4775352;
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 get successfully.");
}
}
I hope it can help you...