我有一個函數可以計算兩個GPS座標之間的距離。然後我得到數據庫中的所有座標,並循環遍歷它們以獲得當前和前一個之間的距離,然後將其添加到特定GPS設備的數組中。由於某種原因,它返回NaN。我曾嘗試將它轉換爲double,int和四捨五入的數字。PHP返回NaN
這是我的PHP代碼:
function distance($lat1, $lon1, $lat2, $lon2) {
$lat1 = round($lat1, 3);
$lon1 = round($lon1, 3);
$lat2 = round($lat2, 3);
$lon2 = round($lon2, 3);
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
if($miles < 0) $miles = $miles * -1;
return ($miles * 1.609344);
}
$this->db->query("SELECT * FROM `gps_loc` WHERE `imeiN`='" . $sql . "' AND `updatetime`>=$timeLimit ORDER BY `_id` DESC");
$dist = array();
$dist2 = array();
while($row = $this->db->getResults()) {
$dist2[$row['imeiN']] = 0;
$dist[$row['imeiN']][]["lat"] = $row['lat'];
$dist[$row['imeiN']][count($dist[$row['imeiN']]) - 1]["lng"] = $row['lon'];
}
foreach($dist as $key=>$d) {
$a = 0;
$b = 0;
foreach($dist[$key] as $n) {
if($a > 0) {
$dist2[$key] += $this->distance($n['lat'], $n['lng'], $dist[$key][$a - 1]['lat'], $dist[$key][$a - 1]['lng']);
}
$a++;
}
}
echo json_encode($dist2);
你能更詳細地顯示出什麼時候出現錯誤嗎? – 2012-01-02 01:28:42
你確定你從數據庫中得到的值是數字而不是字符串嗎? – Chad 2012-01-02 01:30:29
我建議在距離()公式的每個階段加入調試輸出,準確地確定在哪裏生成nan。 – 2012-01-02 01:34:23