March 7, 2012

How do I Measure distance using php?

Question by Justin Petty

I should start of by saying that I’m still pretty green when it comes to PHP, so please be patient with me. I’m trying to figure out the distance between two latitudes and longitudes using php. I found a bunch of scripts online but, however when I try to test them I get the same distance no matter what latitudes and longitudes I use. I’m sure it’s something probably on my part, so I’ll just post what I have so far.

$lat1 = "29.140762";
$lon1 = "-91.639243";

$lat2 = "29.136275";
$lon2 = "-91.635524";

function distance($lat1, $lon1, $lat2, $lon2, $unit) {
    $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);
    } else if ($unit == "N") {
        return ($miles * 0.8684);
    } else {
        return $miles;
    }
}

// Miles
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles<br><br>";

//Kilometers
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers<br><br>";

//Nautical miles
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles";

Answer by rwilliams

I’m guessing that you’ve hard coded your inputs and are just changing the variables at the top of the page and expecting new results. Those variables don’t do anything currently. Try the changes I’ve made below to your function calls, now the variables will be recognized.

// Miles
echo distance($lat1, $lon1, $lat2, $lon2, "m") . " miles<br><br>";

//Kilometers
echo distance($lat1, $lon1, $lat2, $lon2, "k") . " kilometers<br><br>";

//Nautical miles
echo distance($lat1, $lon1, $lat2, $lon2, "n") . " nautical miles";

Answer by Starx

NO it does not

Just tested it and outputs

262.67779380543 miles

422.73893139401 kilometers

228.10939614064 nautical miles

Update

Here is another output when using 
// Miles
echo distance(35.9697, -96.80322, 29.46786, -98.53506, "m") . " miles<br><br>";

//Kilometers
echo distance(35.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers<br><br>";

//Nautical miles
echo distance(35.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles";

460.32704312505 miles

740.82456489105 kilometers

399.7480042498 nautical miles

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!