PDA

View Full Version : Basic Distance Calculation Script


Peter
08-23-2007, 12:32 AM
This is a very basic version. There is no support provided for this code. Use at your own risk.


/***********************
$lat1 = latitude of point 1
$lng1 = longitude of point 1
$lat2 = latitude of point 2
$lng2 = longitude of point 2
***********************/

$lat1 = 37.391436;
$lng1 = -121.995964;
$lat2 = 37.385980;
$lng2 = -121.976737;

$theta = $lng1 - $lng2;
$distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$distance = acos($distance);
$distance = rad2deg($distance);

$miles = $distance * 60 * 1.1515;
$kilometers = $miles * 1.609344;
$nautical = $miles * 0.8684;

echo $miles;

andrewd
08-23-2007, 12:50 AM
Nice one. I was working with this the other week for a client and found there is a deviation of up to 5km using scripts like that depending on the coordinates used as the earth is not spherical but ellipsoidal.

There are one or two options to achieve more accurate results, but they come with a larger operational overhead on your server. The most accurate is a PHP implementation of the Vincenty formula.

I am happy to post here if anyone is interested in more accurate results, but I can't see it being a major requirement for ILance users unless you are seriously customising for other purposes :)

vsv
08-23-2007, 02:41 AM
Hi,

http://distance.ilance.com only provides distance calculation for US and Canada, still there are so many other countries where ilance software is used. As I mentioned into an older post, distance calculation can be done using gps coordinates (since those coordinates become more and more available).
It would be very useful the implementation of such a feature simply by adding a field where you may enter all the locations of your business and ... voila.


Regards,
Sorin