


Implementing the Haversine Formula in PHP for Geospatial Distance Calculation
Jul 30, 2025 am 04:49 AMTo calculate the distance between two points on the earth, use the Haversine formula instead of the plane geometry, because the earth is approximately a sphere. 1. The Haversine formula calculates the distance of the large circle by latitude and longitude (converted to radians). The formula is: a = sin2(Δφ/2) cos φ? ? cos φ? ? sin2(Δλ/2), c = 2 ? atan2(√a, √(1?a)), d = R ? c, where R is the average radius of the earth (6371 kilometers). 2. When implemented in PHP, first convert the latitude and longitude from decimal system to radians, calculate the difference, substitute the formula to find the distance, and select the units of kilometers or miles through the parameters. 3. Use examples to show that the distance between New York and Los Angeles is about 3944 kilometers or 2451 miles. 4. Notes include: the formula accuracy is within 0.5%, which is suitable for most scenarios; when processing large amounts of data, you should first use bounding box filtering to improve performance; ensure that the input is decimal and effective (latitude -90 to 90, longitude -180 to 180); database queries can be roughly screened first. 5. If you need higher accuracy, you can consider the Vincenty formula, but Haversine has achieved a good balance between simplicity and accuracy, and is suitable for web applications without relying on external APIs to implement location functions.
Calculating the distance between two points on Earth isn't as simple as using flat-plane geometry—because Earth is (roughly) a sphere. That's where the Haversine formula comes in. It calculates the great-circle distance between two points on a sphere given their latitude and longitude in decimal degrees. In PHP, this is especially useful for location-based apps like finding neary stores, sorting users by proximity, or filtering results on a map.

Here's how to implement the Haversine formula in PHP accurately and efficiently.
? What Is the Haversine Formula?
The Haversine formula is:

a = sin2(Δφ/2) cos φ? ? cos φ? ? sin2(Δλ/2) c = 2 ? atan2( √a, √(1?a) ) d = R ? c
Where:
- φ is latitude (in radians)
- λ is longitude (in radians)
- Δφ is the difference in latitudes
- Δλ is the difference in longitudes
- R is Earth's radius (mean radius = 6,371 km)
The result d
is the distance in kilometers.

? PHP Implementation
Here's a clean, reusable PHP function:
function haseversineDistance($lat1, $lon1, $lat2, $lon2, $unit = 'km') { // Convert latitude and longitude from degrees to radians $lat1 = deg2rad($lat1); $lon1 = deg2rad($lon1); $lat2 = deg2rad($lat2); $lon2 = deg2rad($lon2); // Difference in coordinates $deltaLat = $lat2 - $lat1; $deltaLon = $lon2 - $lon1; // Haversine formula $a = sin($deltaLat / 2) * sin($deltaLat / 2) cos($lat1) * cos($lat2) * sin($deltaLon / 2) * sin($deltaLon / 2); $c = 2 * atan2(sqrt($a), sqrt(1 - $a)); // Radius of Earth in kilometers (use 3956 for miles) $radius = ($unit === 'mi') ? 3956 : 6371; $distance = $radius * $c; return $distance; }
?? How to Use It
// Example: Distance between New York and Los Angeles $ny = ['lat' => 40.7128, 'lon' => -74.0060]; $la = ['lat' => 34.0522, 'lon' => -118.2437]; $distanceKm = haveversineDistance($ny['lat'], $ny['lon'], $la['lat'], $la['lon']); $distanceMi = hasersineDistance($ny['lat'], $ny['lon'], $la['lat'], $la['lon'], 'mi'); echo "Distance: " . round($distanceKm, 2) . " km\n"; // ~3944 km echo "Distance: " . round($distanceMi, 2) . " mi\n"; // ~2451 mi
?? Key Considerations
- Accuracy : The Haversine formula assumes a spherical Earth. It's accurate to within ~0.5% for most use cases.
- Performance : For large datasets (eg, thousands of locations), consider limiting the search with a bounding box first.
- Units : Easyly extendable to nautical miles or meters by changing the Earth radius.
- Data Types : Ensure lat/lon inputs are in decimal degrees (eg,
40.7128
, not DMS).
You can optimize performance when querying a database by pre-filtering with a rough bounding box:
-- Rough filter before applying Haversine WHERE lat BETWEEN ? AND ? AND lon BETWEEN ? AND ?
Then apply the Haversine formula only to the filtered set.
? Final Notes
- Always validate input coordinates (eg, lat between -90 and 90, lon between -180 and 180).
- Use
float
precision appropriately—PHP handles this well, but database storage matters. - For higher precision (eg, surveying), consider Vincenty's formula—but it's much more complex.
The Haversine formula strikes a great balance between simplicity and accuracy for web applications.
Basically, with this function, you can add location-aware features to your PHP app without relying on external APIs. Just plug in the coordinates and go.
The above is the detailed content of Implementing the Haversine Formula in PHP for Geospatial Distance Calculation. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Floating point numbers are inaccurate is a common problem in PHP. The answer is that it uses IEEE754 double-precision format, which makes decimal decimals unable to be accurately represented; numbers such as 1.0.1 or 0.2 are infinite loop decimals in binary, and the computer needs to truncate them to cause errors; 2. When comparing floating point numbers, you should use tolerance instead of ==, such as abs($a-$b)

round()uses"roundhalftoeven",not"roundhalfup",soround(2.5)returns2andround(3.5)returns4tominimizestatisticalbias,whichmaysurprisethoseexpectingtraditionalrounding.2.Floating-pointrepresentationerrorscausenumberslike2.675tobestored

BCMathisessentialforaccuratecryptocurrencycalculationsinPHPbecausefloating-pointarithmeticintroducesunacceptableroundingerrors.1.Floating-pointnumberslike0.1 0.2yieldimpreciseresults(e.g.,0.30000000000000004),whichisproblematicincryptowhereprecisionu

AvectorinPHPgraphicsrepresentsposition,direction,orvelocityusingaclasslikeVector3Dwithx,y,zcomponents.2.Basicoperationsincludeaddition,subtraction,scalarmultiplication,anddivisionformovementandscaling.3.MagnitudeiscalculatedviathePythagoreantheorem,a

GMPisessentialforhandlinglargeintegersinPHPbeyondnativelimits.1.GMPenablesarbitrary-precisionintegerarithmeticusingoptimizedClibraries,unlikenativeintegersthatoverfloworBCMaththatisslowerandstring-based.2.UseGMPforheavyintegeroperationslikefactorials

ModulararithmeticisessentialinPHPcryptographicapplicationsdespitePHPnotbeingahigh-performancelanguage;2.Itunderpinspublic-keysystemslikeRSAandDiffie-Hellmanthroughoperationssuchasmodularexponentiationandinverses;3.PHP’snative%operatorfailswithlargecr

Calculate the mean: Use array_sum() to divide by the number of elements to get the mean; 2. Calculate the median: After sorting, take the intermediate value, and take the average of the two intermediate numbers when there are even elements; 3. Calculate the standard deviation: first find the mean, then calculate the average of the squared difference between each value and the mean (the sample is n-1), and finally take the square root; by encapsulating these three functions, basic statistical tools can be constructed, suitable for the analysis of small and medium-sized data, and pay attention to processing empty arrays and non-numerical inputs, and finally realize the core statistical features of the data without relying on external libraries.

GMPisessentialforhandlinglargenumbersinPHPthatexceedstandardintegerlimits,suchasinfactorialandFibonaccicalculations,where1itenablesarbitrary-precisionarithmeticforaccurateresults;2itsupportsefficientcomputationoflargefactorialsusinggmp_init,gmp_mul,a
