Calculating Distance Between Coordinates in PHP
Determining the distance between geographical coordinates is a common task in web development. However, it's crucial to avoid unnecessary API calls and implement efficient calculation methods.
One popular formula for measuring distance is the Haversine formula. It uses the latitude and longitude of two points to calculate the distance between them, taking into account the spherical shape of the Earth.
While you've provided an implementation of the Haversine formula, it may yield unreliable results. To investigate the issue, let's review the formula and identify potential errors:
class CoordDistance { [...] public function DistAB() { $delta_lat = $this->lat_b - $this->lat_a; $delta_lon = $this->lon_b - $this->lon_a; $earth_radius = 6372.795477598; $alpha = $delta_lat / 2; $beta = $delta_lon / 2; $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)); $c = asin(min(1, sqrt($a))); $distance = 2 * $earth_radius * $c; $distance = round($distance, 4); $this->measure = $distance; } [...] }
To enhance the reliability of your distance calculations, consider the following suggestions:
Haversine Formula with Improved Precision:
function haversineGreatCircleDistance(float $latitudeFrom, float $longitudeFrom, float $latitudeTo, float $longitudeTo, float $earthRadius = 6371000.0) { ... $angle = 2 * asin(sqrt(pow(sin($latDelta / 2.0), 2) + cos($latFrom) * cos($latTo) * pow(sin($lonDelta / 2.0), 2))); return $angle * $earthRadius; }
Vincenty Formula:
function vincentyGreatCircleDistance(float $latitudeFrom, float $longitudeFrom, float $latitudeTo, float $longitudeTo, float $earthRadius = 6371000.0) { ... $a = pow(cos($latTo) * sin($lonDelta), 2) + pow(cos($latFrom) * sin($latTo) - sin($latFrom) * cos($latTo) * cos($lonDelta), 2); $b = sin($latFrom) * sin($latTo) + cos($latFrom) * cos($latTo) * cos($lonDelta); $angle = atan2(sqrt($a), $b); return $angle * $earthRadius; }
By implementing these improved formulas, you can obtain more accurate distance measurements between coordinates in PHP, even for large distances or points near antipodal points.
The above is the detailed content of How Can I Accurately Calculate the Distance Between Two Geographical Coordinates in PHP?. For more information, please follow other related articles on the PHP Chinese website!