PHPRO.ORG

This function is for getting the distance between two points on the earths surface, and should not be used to calculate linear distances. To calculate linear distances use the function at http://www.phpro.org/examples/Get-Linear-Distance.php

In this example the co-ordinates are taken form the cities database located at http://www.phpro.org/examples/US-Cities-Zip-Codes.html. We have chosen Barcelona and High Springs, Florida for the example.

The function is called getRiemannDistance() in honour of Bernhard Riemann, who in the nineteenth centuary first formulated spherical and hyperbolic geometry. Thanks Bernhard, you're a rock.


<?php

/**
 *
 * @get distance from latitude and longitute
 *
 * @param float $lat_from
 *
 * @param float $long_from
 *
 * @param float $lat_to
 *
 * @param float *long_to
 *
 * @param $unit options k, m, n, Default k
 *
 * @return float
 *
 */
 
function getRiemannDistance($lat_from$long_from$lat_to$long_to$unit='k'){
 
/*** distance unit ***/
 
switch ($unit):
 
/*** miles ***/
 
case 'm':
    
$unit 3963;
    break;
 
/*** nautical miles ***/
 
case 'n':
    
$unit 3444;
    break;
 default:
    
/*** kilometers ***/
    
$unit 6371;
 endswitch;

 
/*** 1 degree = 0.017453292519943 radius ***/
 
$degreeRadius deg2rad(1);
 
 
/*** convert longitude and latitude to radians ***/
 
$lat_from  *= $degreeRadius;
 
$long_from *= $degreeRadius;
 
$lat_to    *= $degreeRadius;
 
$long_to   *= $degreeRadius;
 
 
/*** apply the Great Circle Distance Formula ***/
 
$dist sin($lat_from) * sin($lat_to) + cos($lat_from)
 * 
cos($lat_to) * cos($long_from $long_to);
 
 
/*** radius of earth * arc cosine ***/
 
return ($unit acos($dist));
}

/*** example usage ***/



/*** Barcelona ***/
$lat_from 18.4525;
$long_from = -66.538889;

/*** High Springs Florida ***/
$lat_to 29.841022;
$long_to = -82.615628;

/*** calculate the distance in miles ***/
$distance getRiemannDistance($lat_from$long_from$lat_to$long_to'm');

/*** round it off and echo ***/
echo round$distance ) . ' miles';
?>