How to Calculate distance between two points in php by passing latitude and longitude

In this quick tutorial I am going to share a quick php function to Calculate distance between two points in php using latitude and longitude,This below function calculates the distance between two points.
Passed to function:
lat1, lon1 = Latitude and Longitude of point 1 (in decimal degrees)
lat2, lon2 = Latitude and Longitude of point 2 (in decimal degrees)



Here is the function.

function calDistance($lat1, $lon1, $lat2, $lon2) {
  	$theta = $lon1 - $lon2;
   	$miles = (sin(deg2rad($lat1)) * sin(deg2rad($lat2))) + (cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)));
   	$miles = acos($miles);
   	$miles = rad2deg($miles);
  	$result['miles'] = $miles * 60 * 1.1515;
   	$result['feet'] = $result['miles'] * 5280;
   	$result['yards'] = $result['feet'] / 3;
   	$result['kilometers'] = $result['miles'] * 1.609344;
  	$result['meters'] = $result['kilometers'] * 1000;
  	return $result; 
}

Example.

$distance = calDistance($lat1='28.7041', $lon1='77.1025', $lat2='26.5041', $lon1='75.0025' );
var_dump($distance);
/*
OUTPUT:
array(5) { ["miles"]=> float(199.07401385446) ["feet"]=> float(1051110.7931515) ["yards"]=> float(350370.26438384) ["kilometers"]=> float(320.37856975259) ["meters"]=> float(320378.56975259) }
*/



If you like this post please don’t forget to subscribe my public notebook for more useful stuff

Enter your email address to subscribe my public notebook..!!

Join 21,007 other subscribers

Posted in: PHP

2 Replies to “How to Calculate distance between two points in php by passing latitude and longitude”

  1. In this function you mention the variables $kilometers and $feet but neither are anywhere to be found.
    Can you explain it to me, please?
    Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.