# Calculate the distance between longitudes and latitudes in PHP

##### Author: George Harrison-Webb

Published:

Creating an as the crow flies distance tool within PHP is very simple and it stops you needing to have to use APIs

Prerequisits:

Basic PHP knowledge

Using this Haversine formulae is quick to implement in only a few lines of code'

Looks complex? - Let's break it down

First, take your longitudes and latitudes to compare distances from.

*You could use an API to convert an address to long and lats*

```
$lat1=*Your latitude*;
$lng1=*Your longitude*;
$lat2=*Your latitude*;
$lng2=*Your longitude*;
```

We need to set the radius of the earth - here I am using 6,378,137km ```
$radius = 6378137;
```

Finally, using the following function, taking all the previously set variables, we will be using the Haversine formulae to calculate the distance between the 2 given coordinates.

```
function computeDistance($lat1, $lng1, $lat2, $lng2, $radius)
{
static $x = M_PI / 180;
$lat1 *= $x; $lng1 *= $x;
$lat2 *= $x; $lng2 *= $x;
$distance = 2 * asin(sqrt(pow(sin(($lat1 - $lat2) / 2), 2) + cos($lat1) * cos($lat2) * pow(sin(($lng1 - $lng2) / 2), 2)));
$meters= $distance * $radius;
$miles = round($meters * 0.00062137, 1);
return $miles;
}
```

After calling this function, it will give us the distance between 2 coordinates in miles, which you can of course adjust; depending on the measure you require