Home >Backend Development >PHP Tutorial >How to Accurately Calculate Distances Between Geographical Coordinates in PHP?

How to Accurately Calculate Distances Between Geographical Coordinates in PHP?

DDD
DDDOriginal
2024-12-06 14:51:10967browse

How to Accurately Calculate Distances Between Geographical Coordinates in PHP?

Measuring Distance between Coordinates in PHP

Introduction

Calculating the distance between geographical coordinates is a fundamental task in various applications. One common approach is to employ the Haversine formula. However, it can yield inaccurate results, especially for antipodal points. This article explores an alternative method using the Vincenty formula, which provides more reliable results for all distances.

Implementation

The provided PHP code attempts to implement the Haversine formula for calculating distances. However, it may encounter inaccuracies due to rounding errors when dealing with large distances. Instead, we recommend using the Vincenty formula, as shown in the code snippet below:

public static function vincentyGreatCircleDistance(
  $latitudeFrom, $longitudeFrom, $latitudeTo, $longitudeTo, $earthRadius = 6371000)
{
  // Convert from degrees to radians
  $latFrom = deg2rad($latitudeFrom);
  $lonFrom = deg2rad($longitudeFrom);
  $latTo = deg2rad($latitudeTo);
  $lonTo = deg2rad($longitudeTo);

  $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);
  return $angle * $earthRadius;
}

Note:

By default, the distance is calculated in meters using an earth radius of 6371000 meters. To change the unit of measurement, adjust the value of $earthRadius accordingly.

Error Handling

For antipodal points (i.e., points on opposite sides of the Earth), the Vincenty formula provides more accurate results compared to the Haversine formula. However, it's important to note that both formulas can encounter rounding errors or produce inaccurate results for very small distances.

The above is the detailed content of How to Accurately Calculate Distances Between Geographical Coordinates in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn