Sometimes we need to calculate the distance between latitude and longitude. So for calculating the distance from two points, we need latitude and longitude. There are some functions in MySQL to calculate the distance between two points like "ST_Distance", "ST_GeomFromText", "ST_GeomFromText", "ST_Distance_Sphere" etc.

In this tutorial, I will show you, how to calculate distance as kilometers in Laravel using MySQL from latitude and longitude. You can use this code in any PHP-based application cause we are going to use raw SQL to calculate distance. We are going to see the example of find distance between two points using latitude and longitude in SQL using MySQL.

From this tutorial, you will see an example query of st_distance_sphere MySQL in the Laravel application. Just execute this query to get how to calculate distance using latitude and longitude in Laravel.

App\Http\Controllers\TutorialController.php

``````<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class TutorialController extends Controller
{
public function __invoke()
{
return DB::select("SELECT ST_Distance(ST_GeomFromText('POINT(-77.037852 38.898556)', 4326), ST_GeomFromText('POINT(-77.043934 38.897147)', 4326)) / 1000 AS km;");
}
}``````

Now if you run this query, you will see the following output:

``````[
{
"km": 0.6798889670121944
}
]``````

Read also: How To Use Multiple Where Conditions In Laravel?

### Conclusion

I have tried to demonstrate the concept of "ST_Distance", "ST_GeomFromText", "ST_GeomFromText", "ST_Distance_Sphere" etc. in mysql. In this tutorial, we have seen how to calculate distance by latitude and longitude in php laravel application. Now we know laravel calculate distance between two coordinates.

Category : #laravel