Calculating distance between two locations in PHP

Advertisemen

Here is the map between Sydney and Canberra.

It says distance between these two cities is 153 miles or 247 km.
In this tutorial, we are going to learn how to calculate distance between these two cities using PHP.


To start up, create an empty php file and paste these lines of code in it.
<?php
function getDistance($lat1, $lon1, $lat2, $lon2)
{
   
$radius = 6371; // 1
   
$rad = doubleval(M_PI/180.0); // 2
   
$lat1 = doubleval($lat1) * $rad; // 3
   
$lon1 = doubleval($lon1) * $rad;
   
$lat2 = doubleval($lat2) * $rad;
   
$lon2 = doubleval($lon2) * $rad;

   
$latDiff = $lon2 - $lon1;

   
$dist = acos(sin($lat1) * sin($lat2) +
       
cos($lat1) * cos($lat2) * cos($latDiff)); // 4

   
if ($dist < 0)
    {
       
$dist += M_PI;
   
}
   
return $dist = $dist * $radius;
}

// Sydney
$lat1 = -33.8737;
$lon1 = 151.2069;

// Canberra
$lat2 = -35.282;
$lon2 = 149.1287;

$dist = getDistance($lat1, $lon1, $lat2, $lon2);
$formatted = sprintf("%.2f", $dist * 0.621); // 5

echo $formatted." Miles";
?> 
If you take a closer look into the codes above, you will see some of them has commented number next to it so I am going to explain these codes by numbers.

*1, according to wikipedia the radius of Earth is 6371 kms.
*2, we calculate ratio to convert degree to radian.
*3, latitude and longitude are in degree so we convert them into radian
*4, calculating distance in radian then return by converting them into km
*5, Converting kms to miles in the format two values after points, if you want distance in km, just forget this step.

Now, if you run this code in your browser, it should return. 153.02 miles

Thanks....

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D