Find the distance between two places using latitude and longitude in PHP

In this article, we will see how to calculate the distance between two places or points using latitude and longitude in PHP. Basically, the distance is calculated using latitude and longitude(given in degrees).

You may also calculate the distance using Get the distance between two places in PHP with Google Map API

What is the Haversine formula for finding the distance

The distance problem can be solved by using the Haversine formula. The locations are actually two points on the surface of the earth. In order to find the distance, we need the coordinates of the two points.

In order to calculate the distance, we have to convert the latitude and longitude values from degrees to radians.

Latitude in Radians= (Latitude /180) pi radians
=(Latitude * 0.01746031) radians
Longitude in Radians= (Longitude /180) pi radians
=(Longitude * 0.01746031) radians

Apart from that, we also need the radius of the earth which equals to 3,936 miles or 6,378.8 Km.

Distance between two points is,

Distance= [3963.0 * acos((sin(latitude1) * sin(latitude2)) + cos(latitude1) * cos(latitude2) * cos(longitude2 – longitude1))] in miles

Let us implement the above formula in PHP to obtain required output,

Measure distance between two places using latitude and longitude in PHP

<?php

// latitude and longitude of Two Points
\$latitude1 = 19.017656 ;
\$longitude1 = 72.856178;
\$latitude2 = 40.7127;
\$longitude2 = -74.0059;

//Haversine Formula
\$difflong = \$longi2 - \$longi1;
\$difflat = \$lati2 - \$lati1;

\$val = pow(sin(\$difflat/2),2)+cos(\$lati1)*cos(\$lati2)*pow(sin(\$difflong/2),2);

\$res1 =3936* (2 * asin(sqrt(\$val))); //for miles
\$res2 =6378.8 * (2 * asin(sqrt(\$val))); //for kilometers

//display distance in miles
print_r('Distance:'.\$res1.' '.'miles '.'OR '.\$res2.' '.' kilometers');

?>

Output:-

Distance:7748.9344580629 miles OR 12558.156280765 kilometers

In this way, we can calculate the distance between two points using latitude and longitude in PHP.