Reputation: 13051
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? :)
Upvotes: 1
Views: 615
Reputation: 4652
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
Upvotes: 0
Reputation: 23719
According to this answer:
Calculate distance between two latitude-longitude points? (Haversine formula)
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.
Upvotes: 2
Reputation: 12655
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.
Upvotes: 2