1

i've to calculate the distance between

(40.851774999999996,14.268123999999998)

and each coordinates into results of an sql query:

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $key => $value) {
    echo "distance = ". calculateDistance("40.851774999999996","14.268123999999998",$value['lat'],$value['lng'])."<br>"; 
}

Where calculateDistance is

function calculateDistance($targetLat,$targetLng,$currentLat,$currentLng){
    $r    = 6371; // km
    $dLat = $targetLat-$currentLat;
    $dLng = $targetLng-$currentLng; 
    $a    = sin($dLat/2)*sin($dLat/2) + sin($dLng/2)*sin($dLng/2); 
    $c    = 2*atan2(sqrt($a), sqrt(1-$a));
    return $r*$c;
}

it gives me strange result like:

distance = NAN //-> NAN???
distance = 3392.8405117312 // TOO MUCH!
distance = 3392.8405117312 // TOO MUCH!
...

Where is the problem? can someone help me to fix it? :)

Jayyrus
  • 12,961
  • 41
  • 132
  • 214

3 Answers3

2

You need to convert degrees to radians before using it in sin function.

$radians = $degrees * (M_PI/180);

Look at this function, too. It looks a little bit different.

Community
  • 1
  • 1
bitWorking
  • 12,485
  • 1
  • 32
  • 38
2

According to this answer:

Calculate distance between two latitude-longitude points? (Haversine formula)

  1. You don't convert from degrees to radians.
  2. You formula is incorrect:

They say:

 var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2); 

You wrote:

$a = sin($dLat/2)*sin($dLat/2) + sin($dLng/2)*sin($dLng/2); 

The cosine is missing in your code.

Community
  • 1
  • 1
user4035
  • 22,508
  • 11
  • 59
  • 94
0

You are referring to the Haversine formula:

http://en.wikipedia.org/wiki/Haversine_formula

There are plenty of examples and code snippets in these pages:

I've used this snippet in my code, which works very well:

http://www.codecodex.com/wiki/Calculate_distance_between_two_points_on_a_globe#PHP

Filippos Karapetis
  • 4,367
  • 21
  • 39