Calculating distance using lat/long PHP
May 27th, 2008 | by John |After some doing a bit of research on this topic on the web, I was able to find exactly what I was looking for. At first I looked at how to calculate distance from 2 latitude and longitude points mathematically but then tried to find out if anyone else had found a solution using MySql or PHP that I could reuse. Have a look at the solution below.
PHP:
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') {
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) +
(cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) *
cos(deg2rad($theta)));
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
switch($unit) {
case ‘Mi’: break;
case ‘Km’ : $distance = $distance * 1.609344;
}return (round($distance,2));
}
MySQL:
$qry = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) * sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)*pi()/180))))*180/pi())*60*1.1515) as distance FROM `MyTable` WHERE distance <= ".$distance."
Now I wanted to make sure that others are able to benefit from the help that the author of
The marketing technology blog provide me.

2 Responses to “Calculating distance using lat/long PHP”
By Douglas Karr on May 28, 2008 | Reply
Thanks for the kind mention!
By Harry Hobson on Jun 3, 2008 | Reply
Thanks so much for this!