# Calculate Distance Between Two Geographical Points With PHP

16th June 2008 - 2 minutes read time

Use the following function to work out the distance between two geographical points. Geographical points are usually longitude and latitude, in degrees. The first thing to do is to convert these values into radians (using the deg2rad() PHP function) so that we can work with them. The four basic parameters used are the longitude and latitude values for the two points. The optional fifth value is to have the end value returned in miles, rather than kilometres.

``````function getDistance(\$a_lat, \$a_lng, \$b_lat, \$b_lng, \$mi=false)
{
if(\$a_lat==\$b_lat && \$a_lng==\$b_lng){
// two distances are the same
return 0;
}
if ( (sin(\$b_lat)*sin(\$a_lat) + cos(\$b_lat)*cos(\$a_lat)*cos(\$b_lng-\$a_lng))>1 ) {
return \$radius * acos(1);
};
return \$radius * acos(sin(\$b_lat)*sin(\$a_lat)+cos(\$b_lat)*cos(\$a_lat)*cos(\$b_lng-\$a_lng));
}``````

Here are some examples of the code in action.

``````echo getDistance(40.995827,-94.370559,63.439031,84.723732); // 8402.1830291634
echo getDistance(-23.782270,134.078645,-23.782626,134.065365); // 1.3518544215203``````

To print out these results in miles you can set the fifth parameter to be true.

``````echo getDistance(40.995827,-94.370559,63.439031,84.723732,true); // 13521.830575736
echo getDistance(-23.782270,134.078645,-23.782626,134.065365,true); // 2.175571085206``````