Home >Backend Development >PHP Tutorial >How Can I Calculate Geographic Distance Using PHP\'s Haversine and Vincenty Formulas?
Determining Geographic Distance with PHP Coordinates
Calculating the distance between two geographical coordinates involves the Haversine or Vincenty formulas.
Haversine Formula
The Haversine formula, implemented in the following PHP code:
class CoordDistance { // Latitude and longitude of points A and B public $lat_a, $lon_a, $lat_b, $lon_b; public $earth_radius = 6372.795477598; public $distance; public function DistAB() { $latDelta = $this->lat_b - $this->lat_a; $lonDelta = $this->lon_b - $this->lon_a; $alpha = $latDelta / 2; $beta = $lonDelta / 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 * $this->earth_radius * $c; $this->distance = $distance; } }
Vincenty Formula
For antipodal points, the Vincenty formula is more accurate:
class CoordDistance { // Latitude and longitude of points A and B public $lat_a, $lon_a, $lat_b, $lon_b; public $earth_radius = 6371000; public $distance; public function DistAB() { // Convert to radians $latFrom = deg2rad($this->lat_a); $lonFrom = deg2rad($this->lon_a); $latTo = deg2rad($this->lat_b); $lonTo = deg2rad($this->lon_b); $lonDelta = $lonTo - $lonFrom; $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); $distance = $angle * $this->earth_radius; $this->distance = $distance; } }
Both formulas return the distance in the same unit of measurement as the provided earth's radius.
The above is the detailed content of How Can I Calculate Geographic Distance Using PHP\'s Haversine and Vincenty Formulas?. For more information, please follow other related articles on the PHP Chinese website!