Calculate Distance between two latitude and longitude without google API

This code is used for calculate distance between two latitude and longitude using PHP.

  • Without any google API calculate distance.
  • Pass source latitude longitude and destination latitude and longitude.
  • Easy to implement.
  • Not required any Google API.
  • You can also get result on meter and Kilometer and  Nautical Miles.
  • Pass latitude and longitude.

 

<?php

function distance($lat1, $lon1, $lat2, $lon2, $unit) {
  if (($lat1 == $lat2) && ($lon1 == $lon2)) {
    return 0;
  }
  else {
    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $unit = strtoupper($unit);

    if ($unit == "K") {
      //return ($miles * 1.609344);
	  $temp=$miles * 1.609344;
	  return number_format((float)$temp, 2, '.', '');
	  
    } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
      return $miles;
    }
  }
}




//echo distance(21.2514, 81.6296, 21.3320,82.997, "K") . " Kilometers<br>";
//echo distance(21.2589197,81.6577905, 21.2242928,81.619884, "K") . " Kilometers<br>";
echo distance(21.2576367426664,81.6361305769533, 21.2737254286185,81.6667449753732, "K") . " Kilometers<br>";
//echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
//echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

?>

Leave a Reply

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