views:

42

answers:

0

I need to use this function form php directly to mysql i'm currently using a simpler formula but this one works better, the porpose is to find the geodetic distance from two point on a map, so basically in my mysql i have a table with cities and avery city has its own lat,long values...

his is the formula i would translate

function distance($lat1, $lng1, $lat2, $lng2)
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    return ($km);
}

and this is what I'm currently using

SELECT *, 
    ACOS(SIN($lat1)*SIN(cities_tb.lat)
    + COS($lat1)*COS(cities_tb.lat)*COS(cities_tb.lon-$lon1))*6371 as distance
FROM cities_tb                      
    ...etc...

where $lat1 and $lon1 are values coming from the PHP page