As a pilot by trade, and as somebody that builds a lot of aviation based applications, it was handy coming across a function that calculates the distance between two points based on longitude and latitude. I’ve just used ‘elements’ of this PHP code in an Android based application I’m working on.
The function, originally published by ZipCodeWorld.com, will output a distance in either miles, kilometers or nautical miles and it is very easy to add another means of measurement if those three don’t agree with you.
It’s very easy to build a simple form to pass the data from one page to a working script (as I have done).
The function
<?php
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;
}
}
?>
Usage
Usage is simple and rather self explanatory based on the code below. South latitudes are negative and east longitudes are positive. The latitude and longitude is entered as decimal degrees.
<?php // Miles echo distance(32.9697, -96.80322, 29.46786, -98.53506, "m") . " miles
"; //Kilometers echo distance(32.9697, -96.80322, 29.46786, -98.53506, "k") . " kilometers
"; //Nautical miles echo distance(32.9697, -96.80322, 29.46786, -98.53506, "n") . " nautical miles
"; ?>
Other applications
If you wanted to be very clever, you could use the PHP code below to extract latitude and longitude from a street address via the Google Maps API; then pass that data to the script above to generate a distance.
<?php
function getLatLong($address){
if (!is_string($address))die("All Addresses must be passed as a string");
$_url = sprintf('http://maps.google.com/maps?output=js&q=%s',rawurlencode($address));
$_result = false;
if($_result = file_get_contents($_url)) {
if(strpos($_result,'errortips') > 1 || strpos($_result,'Did you mean:') !== false) return false;
preg_match('!center:\s*{lat:\s*(-?\d+\.\d+),lng:\s*(-?\d+\.\d+)}!U', $_result, $_match);
$_coords['lat'] = $_match[1];
$_coords['long'] = $_match[2];
}
return $_coords;
}
?>
|
|
If you liked this article, you may also like:


Great articles, it helped me added a distance measurement for my website… thx alot :)
thanks
function degree_to_miles($lat1, $lon1, $lat2, $lon2) {
return rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 – $lon2)))) * 60 * 1.1515;
}