Let's say I have two coordinates a
and b
that both consist of a latitude and a longitude. How can I check if a third coordinate c
is in between coordinate a
and b
using PHP?
With other words: When I connect a
and b
with a line, how can I tell if coordinate c
is exactly on that line?
I already found an answer solving this for simple X and Y coordinates using the cross product and dot product with Python, see here: https://stackoverflow.com/a/328122
But it seems like it's more complicated using coordinates with a lot of decimal places in PHP like its the case with latitudes and longitudes due to the limited precision for floating point numbers in PHP.
So here is a basic example that does not work for the above solution:
// Copied from the Python solution
public function isBetweenPoints($aLat, $aLng, $bLat, $bLng, $cLat, $cLng) {
$crossProduct = ($cLat - $aLat) * ($bLng - $aLng) - ($cLng - $aLng) * ($bLat - $aLat);
if (abs($crossProduct) < PHP_FLOAT_EPSILON) {
return false;
}
$dotProduct = ($cLng - $aLng) * ($bLng - $aLng) + ($cLat - $aLat)*($bLat - $aLat);
if ($dotProduct < 0) {
return false;
}
$squaredLength = ($bLng - $aLng)*($bLng - $aLng) + ($bLat - $aLat)*($bLat - $aLat);
return !($dotProduct > $squaredLength);
}
$aLat = 48.14723956724038;
$aLng = 11.514418017613934;
$bLat = 48.14722882951992;
$bLng = 11.51386548255687;
$cLat = 48.147645056105120;
$cLng = 11.514326333999636;
// Returns true, even if the point c is not between a and b
isBetweenPoints($aLat, $aLng, $bLat, $bLng, $cLat, $cLng);
To better understand that isBetweenPoints
in the above example should return false, here is a corresponding image on which $latLngA
and $latLngB
is represented by the green line at the bottom and $latLngC
by the marker at the top: