php-distance is a simple PHP library for calculating the distance between two geographical points on Earth. It supports different Earth radius values and various distance calculation formulas.
Use Composer to install the library:
composer require lounisbou/phpdistanceDefine Points
Define geographical points using the Point class:
use PHPDistance\Point;
$start = new Point(52.5200, 13.4050); // Berlin
$end = new Point(48.8566, 2.3522); // ParisUse the Route class with the HaversineCalculator to calculate the distance using the Haversine formula:
use PHPDistance\Route;
use PHPDistance\HaversineCalculator;
use PHPDistance\Enums\EarthRadius;
$start = new Point(52.5200, 13.4050); // Berlin
$end = new Point(48.8566, 2.3522); // Paris
$calculator = new HaversineCalculator(EarthRadius::MEAN_RADIUS);
$route = new Route($start, $end, $calculator);
$distance = Route::getHumanReadableDistance($haversineCalculator->calculate($route));
echo "Distance using Haversine formula with mean radius: " . $distance;Use the Route class with the VincentyCalculator to calculate the distance using Vincenty's formula:
use PHPDistance\Route;
use PHPDistance\VincentyCalculator;
$start = new Point(52.5200, 13.4050); // Berlin
$end = new Point(48.8566, 2.3522); // Paris
$calculator = new VincentyCalculator();
$route = new Route($start, $end, $calculator);
$distance = Route::getHumanReadableDistance($vincentyCalculator->calculate($route));
echo "Distance using Vincenty formula: " . $distance;The Haversine formula is an equation giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is useful for calculating the shortest distance over the earth's surface.
Vincenty's formulae are two related iterative methods used in geodesy to calculate the distance between two points on the surface of an ellipsoid. They are accurate for long distances.
The MySQL formula is a simplified version of the Haversine formula that can be used in MySQL queries to calculate distances between two points.
You can specify a custom Earth radius if needed:
$customRadius = 6356752.3142; // Custom radius in meters
$calculator = new HaversineCalculator($customRadius);
$route = new Route($start, $end, $calculator);
echo "Distance using Haversine formula with custom radius: " . $route->calculateDistance() . " meters\n";You can extend the library by adding more distance calculation formulas. Implement the DistanceCalculatorInterface to create a new calculator:
use PHPDistance\Point;
use PHPDistance\DistanceCalculatorInterface;
class NewFormulaCalculator implements DistanceCalculatorInterface
{
public function calculate(Point $from, Point $to): int
{
// Implement the new formula here
return 0; // Placeholder
}
}Contributions are welcome! Please feel free to submit a Pull Request or open an Issue on GitHub.
This library is licensed under the MIT License. See the LICENSE file for details.