# Laravel Made Easy: Finding Distance from Longitude & Latitude

0

## How to get distance from two Longitude and Latitude in Laravel without any third party API

In this article we will see how can we find distance between to places on the basis of their longitude and latitude without using any third party package or google API in Laravel .

We will take an example where we will take longitude and latitude of two places ( India and USA ) and we will try to findout the distance between the two place in Kilometers , Further you can convert the Kilometer to any other unit .

As Google's API is now paid , you can use this method to get distance between two places if you have their longitude and latitude . Let's dive in and see how to do this .

### Step 1 - Collect Longitude and Latitude :

In this case i am assuming that you have longitude and latitude of two places . For example i have longitude and latitude of two places ( India and USA ) .

```\$longitude_1 = 20.593683; // longitude of India
\$latittude_1 = 78.962883; // latitude of India
\$longitude_2 = 37.090240; //longitude of USA
\$latittude_2 = -95.712891; //latitude of USA
```

### Step 2 - Use the following code :

Now simply use the following code on your controller to get distance.

```public function trackDistance()
{
\$longitude_1 = 20.593683;
\$latittude_1 = 78.962883;
\$longitude_2 = 37.090240;
\$latittude_2 = -95.712891;
\$unit = "k"; // K for kilometer

function distance(\$latittude_1, \$longitude_1, \$latittude_2, \$longitude_2, \$unit) {
if ((\$latittude_1 == \$latittude_2) && (\$latittude_1 == \$longitude_2)) {
return 0;
}
else {
\$theta = \$longitude_1 - \$longitude_2;
\$dist = acos(\$dist);
\$miles = \$dist * 60 * 1.1515;
\$unit = strtoupper(\$unit);

if (\$unit == "K") {
return (\$miles * 1.609344);
}
}
}

\$distance_in_km = distance(\$latittude_1, \$longitude_1, \$latittude_2, \$longitude_2, \$unit);
return response()->json(['response' => ['code' => '200', 'distance' => \$distance_in_km]]);
}
```

That's it now simply run your route , you will get your distance in kilometers , Note that to get the distance of two place using this code you need to have longitude and latitude of both of the places .

### Output :

In my case i am using Postman to check my response .