I'm trying to calculate the distance between two latitude/longitude coordinates using the equirectangular approximation formula in PHP, but I get different results than the haversine formula (which I know is correct) for certain longitude coordinates.
define('EARTH_RADIUS', 6371);
function equirectangularRad($latFrom, $lngFrom, $latTo, $lngTo) {
$latDelta = $latTo - $latFrom;
$lngDelta = $lngTo - $lngFrom;
$x = $lngDelta * cos(($latFrom + $latTo) * .5);
$radius = sqrt(($x * $x) + ($latDelta * $latDelta));
return $radius * EARTH_RADIUS;
}
Distances always seem to be calculated crossing the prime meridian instead of the shortest distance. i.e. from coordinate (lat=0, long=-180) to (lat=0, long=180) along the equator, the distance should be zero. Instead the function returns the circumference of the earth along the equator; roughly 40030 kilometer.
The problem seems to stem from the calculation of $lngDelta
, but all implementations I can find, for any programming language, uses this same formula. Am I missing some important detail or is this formula truely not a drop-in replacement for haversine (ignoring the obvious accuracy difference)?
For reference; this is the haversine implementation I use:
function haversineRad($latFrom, $lngFrom, $latTo, $lngTo) {
$latDelta = $latTo - $latFrom;
$lngDelta = $lngTo - $lngFrom;
$latSin = sin($latDelta * .5);
$lngSin = sin($lngDelta * .5);
$radius = 2. * asin(sqrt(($latSin * $latSin) + cos($latFrom) * cos($latTo) * ($lngSin * $lngSin)));
return $radius * EARTH_RADIUS;
}
You reuse
latDelta
one of the uses have them added, the other subtracted.http://www.movable-type.co.uk/scripts/latlong.html
have working javascript.
translated ..