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 one and the previous one, then add that to an array for the specific GPS device. For some reason it is return NaN. I have tried casting it as a double, an int, and rounding the number.
Here 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);
The range of sin() and cos() is between -1 and 1. Therefore in your first calculation of $dist the result range is -2 to 2. You then pass this to acos(), whose argument must be between -1 and 1. Thus acos(2) for example gives NaN. Everything else from there gives NaN as well.
I'm not sure what the formula should be exactly, but that's where your NaN is coming from. Double-check your trigonometry.
The algo will produce NaN if points are too close to each other. In that case $dist gets value 1. acos(1) is NaN. All subsequent calculations produce NaN too.
You round coordinates as the first step, so it makes more probable that the values become equal after rounding, and produce NaN.
The values you are pulling from the database may be strings, which would cause this issue.
You may also want to check the issues that Kolink raised in his post.
Is that the spherical law of cosines you're using? I'd switch to the Haversine formula:
function distance($lat1, $lon1, $lat2, $lon2)
{
$radius = 3959; //approximate mean radius of the earth in miles, can change to any unit of measurement, will get results back in that unit
$delta_Rad_Lat = deg2rad($lat2 - $lat1); //Latitude delta in radians
$delta_Rad_Lon = deg2rad($lon2 - $lon1); //Longitude delta in radians
$rad_Lat1 = deg2rad($lat1); //Latitude 1 in radians
$rad_Lat2 = deg2rad($lat2); //Latitude 2 in radians
$sq_Half_Chord = sin($delta_Rad_Lat / 2) * sin($delta_Rad_Lat / 2) + cos($rad_Lat1) * cos($rad_Lat2) * sin($delta_Rad_Lon / 2) * sin($delta_Rad_Lon / 2); //Square of half the chord length
$ang_Dist_Rad = 2 * asin(sqrt($sq_Half_Chord)); //Angular distance in radians
$distance = $radius * $ang_Dist_Rad;
return $distance;
}
You should be able to change the earth's radius to any form of measurement from radius in light years to radius in nanometers and get the proper number back out for the unit used.
Thanks for all the responses here - as a result I made a function which combines to computations and tests for NaN in each, if both are not NaN - it averages the calculation, if one is NaN and the other is not - it uses the one that's valid and gives error report for the coordinates that failed one of the calculation:
function distance_slc($lat1, $lon1, $lat2, $lon2) {
$earth_radius = 3960.00; # in miles
$distance = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon2-$lon1)) ;
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
$distance1 = round($distance, 4);
// use a second method as well and average
$radius = 3959; //approximate mean radius of the earth in miles, can change to any unit of measurement, will get results back in that unit
$delta_Rad_Lat = deg2rad($lat2 - $lat1); //Latitude delta in radians
$delta_Rad_Lon = deg2rad($lon2 - $lon1); //Longitude delta in radians
$rad_Lat1 = deg2rad($lat1); //Latitude 1 in radians
$rad_Lat2 = deg2rad($lat2); //Latitude 2 in radians
$sq_Half_Chord = sin($delta_Rad_Lat / 2) * sin($delta_Rad_Lat / 2) + cos($rad_Lat1) * cos($rad_Lat2) * sin($delta_Rad_Lon / 2) * sin($delta_Rad_Lon / 2); //Square of half the chord length
$ang_Dist_Rad = 2 * asin(sqrt($sq_Half_Chord)); //Angular distance in radians
$distance2 = $radius * $ang_Dist_Rad;
//echo "distance=$distance and distance2=$distance2\n";
$avg_distance=-1;
$distance1=acos(2);
if((!is_nan($distance1)) && (!is_nan($distance2))){
$avg_distance=($distance1+$distance2)/2;
} else {
if(!is_nan($distance1)){
$avg_distance=$distance1;
try{
throw new Exception("distance1=NAN with lat1=$lat1 lat2=$lat2 lon1=$lon1 lon2=$lon2");
} catch(Exception $e){
trigger_error($e->getMessage());
trigger_error($e->getTraceAsString());
}
}
if(!is_nan($distance2)){
$avg_distance=$distance2;
try{
throw new Exception("distance1=NAN with lat1=$lat1 lat2=$lat2 lon1=$lon1 lon2=$lon2");
} catch(Exception $e){
trigger_error($e->getMessage());
trigger_error($e->getTraceAsString());
}
}
}
return $avg_distance;
}
HTH someone in the future as well.
Related
I'm having some trouble computing the distance between two GPS points by their coordinates.
point a
x = 7,2562
y = 47,7434599999999
point b
x = 7,21978
y = 47,73836
I used the Haversine formula as described here. The result I get is 4.09 km.
However, locating those points on a map using a tool like this, I can measure a distance of 2.8 km
Several other formulas I tried also return a result around 4 km.
Any ideas what I would be missing ?
I think is because u are using the function in miles, in Kms you can use something like that:
public static function distance(
array $from,
array $to
) {
if (empty($from['lat']) || empty($to['lat'])) {
return $to['distance'];
}
$latitude1 = (float) $from['lat'];
$latitude2 = (float) $to['lat'];
$longitude1 = (float) $from['lng'];
$longitude2 = (float) $to['lng'];
$theta = $longitude1 - $longitude2;
$distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2)))
+ (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)))
;
$distance = acos($distance);
$distance = rad2deg($distance);
$distance = $distance * 60 * 1.1515;
$distance = (is_nan($distance)) ? 0 : $distance * 1.609344;
return $distance;
}
As pointed out by Roland Starke in the comments, the problem was the order of the coordinates. (7, 47 not 47, 7)
I have a table in mysql with 4 columns:
Latitude_1
Longitude_1
Latitude_2
Longitude_2
Now I want to calculate the heading for all rows to be used in a kml file.
I found this function:
// Takes two sets of geographic coordinates in decimal degrees and produces bearing (azimuth) from the first set of coordinates to the second set.//
public static function bearing($lat1, $lon1, $lat2, $lon2) {
$lat1 = deg2rad($lat1);
$lon1 = deg2rad($lon1);
$lat2 = deg2rad($lat2);
$lon2 = deg2rad($lon2);
$lonDelta = $lon2 - $lon1;
$y = sin($lonDelta) * cos($lat2);
$x = cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($lonDelta);
$brng = atan2($y, $x);
$brng = $brng * (180 / pi());
if ( $brng < 0 ) { $brng += 360; }
return $brng;
}
Now I hope that someone shows me a query that echoes all headings (bearings) of the table based on the above mentioned function
To combine an expression expr, take a look to the mysql math functions and find proper equivalents for php ones - https://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
Simplify your expr if possible
Use your result expression expr in following query SELECT expr FROM your_table
Profit
I have serious performance issues with a distance calculation script.
I have approximately 3000 locations (and this will eventually be doubled) in a database. The database structure is quite complex (categories, subcategories) but with time(); I saw that these query's didn't took much time.
I have a $_GET of latitude and longitude of the user and I use this calculation to determine if the location is within a certain radius:
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$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;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
// some sql queries to get the lat/lon from the locations
if ((distance($_GET["lat"], $_GET["long"], $row3["content"], $row4["content"], "K") . "") < 10) {
//push to multidimensional array
}
$row3["content"] and $row4["content"] are the latitude and longitude values. For 3000 locations, this calculation takes up to 13 seconds!
I read this:
Fastest Way to Find Distance Between Two Lat/Long Points
I think the option to draw a box, based on the $_GET of latitude and longitude could perhaps already remove the current calculation. In the sql queries I can already filter out the locations outside the 10 km range.
But I have 2 questions:
If I change the SQL to something like this: ... WHERE LAT >= x1 AND <= x2, does this affect the time of the query?
In the explanation the writer talks about "units". I've been playing around with the lat/lon values, but how do I actually calculate x1, x2, y1, y2 where the $_GET value is a point in the center with a distance of 10 km?
Thank you.
I was able to reduce the calculation time from 13 seconds to 1 second!
I did this by filtering out with mysql the locations that were not within a 10 km bounding box of my lat/long coordinates.
I used this code:
$rad = 10; // radius of bounding circle in kilometers
$R = 6371; // earth's mean radius, km
// first-cut bounding box (in degrees)
$maxLat = $_GET['lat'] + rad2deg($rad/$R);
$minLat = $_GET['lat'] - rad2deg($rad/$R);
// compensate for degrees longitude getting smaller with increasing latitude
$maxLon = $_GET['long'] + rad2deg($rad/$R/cos(deg2rad($_GET['lat'])));
$minLon = $_GET['long'] - rad2deg($rad/$R/cos(deg2rad($_GET['lat'])));
and I changed my mysql to this:
$sql2 = "SELECT ....WHERE LAT BETWEEN '".$minLat."' AND '".$maxLat."'";
$sql3 = "SELECT ....WHERE LON BETWEEN '".$minLon."' AND '".$maxLon."'";
The rest of my code and calculation is exact the same, but instead of doing 3000 calculations, mysql sweeps out the majority.
I don't know if this approach is 100% mathematically correct, but as far as I see it works very fast with minor changes to my initial coding so for my project it's great.
And of course, the source: http://www.movable-type.co.uk/scripts/latlong-db.html
In php, given a latitude and longitude point, a bearing (in degrees), and a distance (in feet or km or whatever) how do I figure out what the new lat lng point is? here is what I tried, but it's wrong.
function destinationPoint($lat, $lng, $brng, $dist) {
$meters = $dist/3.2808399; // dist in meters
$dist = $meters/1000; // dist in km
$rad = 6371; // earths mean radius
$dist = $dist/$rad; // convert dist to angular distance in radians
$brng = deg2rad($brng); // conver to radians
$lat1 = deg2rad($lat);
$lon1 = deg2rad($lng);
$lat2 = asin(sin($lat1)*cos($dist) + cos($lat1)*sin($dist)*cos($brng) );
$lon2 = $lon1 + atan2(sin($brng)*sin($dist)*cos($lat1),cos($dist)-sin($lat1)*sin($lat2));
$lon2 = ($lon2+3*M_PI) % (2*M_PI) - M_PI; // normalise to -180..+180ยบ
$lat2 = rad2deg($lat2);
$lon2 = rad2deg($lon2);
echo "lat2 = ".$lat2."<br/>";
echo "lon2 = ".$lon2."<br/>";
}
Just change
$lon2 = ($lon2+3*M_PI) % (2*M_PI) - M_PI;
to
$lon2 = fmod($lon2 + 3*M_PI, 2*M_PI) - M_PI;
According to PHP's documentation about the modulus operator (%),
Operands of modulus are converted to integers (by stripping the decimal part) before processing.
fmod "[r]eturns the floating point remainder (modulo) of the division of the arguments."
I have this code to find the distance between two sets of GPS coordinates, I got the code from elsewhere on the net.
function distance($lat1, $lon1, $lat2, $lon2, $unit) {
$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;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
} else if ($unit == "N") {
return ($miles * 0.8684);
} else {
return $miles;
}
}
The ouput returned looks like this: 25.44049 but if I do
$distance_output = distance(-50.12345, 100.1235,-60.12345,120.12345,'km');
echo $distance_output . '<br />;
echo $distance_output - 15.12345;
it outputs like this:
15.12345
1.23639038e10
These are just made up numbers, but you can see the output of distance() looks like a number but then when I subtract the same number from it, it spits out a wierd exponential number. Any ideas?
Thanks a lot
Why is PHP printing my number in scientific notation, when I specified it as .000021?
Use number_format()
I tried your code (you just missed a simple quote), and the output is 1042.1216629565 and 1026.9982129565, seems ok to me.
If I substract 1042.1216629565 to 1042.1216629565, the output becomes 3.092281986028E-11 : note the minus character after the e.
This number is equal to 0.00000000003092281986028, not zero. This difference is common with floating point computation. It can be explained by rounding errors in value binary coding.
See wikipedia : http://en.wikipedia.org/wiki/Floating_point and particularly section about rounding.
If you want to display the result, use number_format()
If you want to compare two floating point values, you'll have to do use something like that :
$epsilon = 1e-6;
if (abs($value1-$value2) <= $epsilon){
}