PHP returns NaN value
P粉914731066
P粉914731066 2024-03-25 17:22:54
0
2
664

I have a function that calculates the distance between two GPS coordinates. I then get all the coordinates from the database and loop through them all to get the distance between the current coordinate and the previous coordinate and then add it to an array for the specific GPS device. For some reason it returns NaN. I've tried converting it to a double, an integer, and rounding the number.

This is my PHP code:

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);

P粉914731066
P粉914731066

reply all(2)
P粉373990857

sin() and cos() range between -1 and 1. Therefore, the first time $dist is evaluated the result range is -2 to 2. This is then passed to acos() whose argument must be between -1 and 1. For example, acos(2) gives NaN . Everything else there also gives NaN.

I'm not sure what the formula is supposed to be, but that's where your NaN is coming from. Check your trigonometric functions carefully.

P粉005134685

The values ​​you extract from the database may be strings, which causes this problem.

You may also want to check out the questions Kolink asked in his post.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template