# Find Distance in km and Miles from latitude and longitude value in PHP

I was wondering How can I find distance between two places using latitude and longitude in PHP. Today I will show you How easily we can calculate the distance between to places in Kilometer and Miles. The example here, takes two values for each place ( latitude and longitude ).

Lets create form to accept latitude and longitude value.

```<form method="get" action="">

<p>
<strong>First location</strong> <span style="font-size:0.8em"><em>(default: Ahmedabad, Gujarat, India)</em></span><br>
Latitude: <input type="text" name="lat1" value="23.0333">
Longitude: <input type="text" name="lon1" value="72.6167"><br>
<span style="font-size:0.8em"><em>Expressed in decimal degrees</em></span>
</p>

<p>
<strong>Second location</strong> <span style="font-size:0.8em"><em>(default: Surat, Gujarat, India)</em></span><br>
Latitude: <input type="text" name="lat2" value="21.1700">
Longitude: <input type="text" name="lon2" value="72.8300"><br>
<span style="font-size:0.8em"><em>Expressed in decimal degrees</em></span>
</p>

<p>
<input type="submit" value="Calculate">
<input type="reset" value="Clear Form">
</p>

<hr>
</form>```

Function to find the distance is as follow:

```function findDistance(\$return_in='km') {
\$Rm = 3961; // mean radius of the earth (miles) at 39 degrees from the equator
\$Rk = 6373; // mean radius of the earth (km) at 39 degrees from the equator

// get values for lat1, lon1, lat2, and lon2
\$t1 = \$_REQUEST['lat1'];
\$n1 = \$_REQUEST['lon1'];
\$t2 = \$_REQUEST['lat2'];
\$n2 = \$_REQUEST['lon2'];

// find the differences between the coordinates
\$dlat = \$lat2 - \$lat1;
\$dlon = \$lon2 - \$lon1;

// here's the heavy lifting
\$a  = (double)pow(sin(\$dlat/2),2) + cos(\$lat1) * cos(\$lat2) * pow(sin(\$dlon/2),2);
\$c  = (double)2 * atan2(sqrt(\$a),sqrt(1-\$a)); // great circle distance in radians
\$dm = \$c * \$Rm; // great circle distance in miles
\$dk = \$c * \$Rk; // great circle distance in km

// round the results down to the nearest 1/1000
\$mi = round( \$dm * 1000) / 1000;
\$km = round( \$dk * 1000) / 1000;

// display the result
if(\$return_in=="miles")
return \$mi;
else
return \$km;
}```

This function accept one parameter which is not mandatory. To get the result in mile pass ‘miles’ as parameter. Otherwise it returns result in kilometer.

Comment here if you have any queries.

Thanks,