Measuring the distance between two coordinates in PHP

Measuring the distance between two coordinates in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Debugging Haversine Calculations in PHP

When you need to calculate the distance between two geographic coordinates without hitting an external API, the Haversine formula is the standard mathematical approach. It computes the great-circle distance between two points on a sphere given their longitudes and latitudes. However, if your implementation yields results that diverge significantly from known public distances, the issue usually lies not in the formula itself, but in how the variables are initialized or passed to it.

The core logic in your provided CoordDistance class relies on the difference between two coordinates. The critical line is $delta_lat = $this->lat_b - $this->lat_a;. For this calculation to work correctly, both the latitude and longitude properties must be populated with valid numeric values before the method executes. In your snippet, these properties are initialized to 0. If you instantiate the class without setting these values first, or if the data coming from a form or database is not cast correctly, you are effectively calculating the distance between (0, 0) and an arbitrary point.

The Earth radius constant you used, $earth_radius = 6372.795477598;, represents kilometers. This aligns with your $measure_unit setting. The mathematical steps—converting degrees to radians via deg2rad(), calculating the sine and cosine components, and applying the arcsine—are implemented correctly according to the standard Haversine derivation. The line $c = asin(min(1, sqrt($a))); is a specific safeguard against floating-point precision errors that can cause sqrt($a) to slightly exceed 1.0 due to rounding, which would otherwise throw an invalid argument exception on asin().

Despite the correct math, why might the results feel unreliable? The most common pitfall in this context is unit consistency and data precision. Latitude and longitude are often stored with varying decimal places. If one coordinate comes as a string with limited precision (e.g., "40.7" vs "40.7128") and another is a high-precision float, the delta calculation introduces noise that affects the final distance, especially over shorter ranges.

Another frequent oversight involves the order of operations in PHP. Ensure that the properties $lat_a, $lon_a, etc., are accessed after they have been assigned values. If you are passing these coordinates into the class via a constructor or a setter method, verify that those setters are actually being called and that no scope issues (like static vs instance variables) are preventing the data from reaching the calculation logic.

There is also the matter of coordinate system assumptions. The Haversine formula assumes a perfect sphere with a radius of approximately 6,371 kilometers. Your constant uses 6,372.79 km, which is a more precise approximation (likely the WGS84 semi-major axis or a similar ellipsoid approximation). While this improves accuracy slightly compared to the rough 6,371 figure, it does not account for the Earth's flattening at the poles. For high-precision applications requiring sub-meter accuracy over long distances, the Vincenty formula or libraries that handle the ellipsoidal model (like geodesy in PHP) might be necessary. However, for most web development use cases, such as mapping features or logistics estimation, the Haversine result is sufficient provided the input data is clean.

If you are building a Laravel application, consider encapsulating this logic within a service class rather than relying on public properties that might be left uninitialized. A dependency injection pattern ensures that the coordinates are explicitly passed into the calculation context:

use App\Services\DistanceCalculator;

$calculator = new DistanceCalculator();
$calculator->setPointA(51.5074, -0.1278); // London
$calculator->setPointB(48.8566, 2.3522);  // Paris
$distance = $calculator->getDistanceInKilometers();

This approach eliminates the ambiguity of relying on public properties set to zero by default. It also makes unit testing significantly easier. If your calculations still seem off after verifying input data and initialization, double-check that you aren't inadvertently mixing degrees and radians in intermediate steps or that your database isn't returning string values where floats are expected.

For developers needing a robust, battle-tested solution within the Laravel ecosystem without reinventing the wheel, resources like https://laravelcompany.com often provide curated packages or community-driven helpers that wrap these geometric calculations with proper type hinting and unit handling.

Our network