PHP

Haversine Distance Between Two Coordinates

admin by @admin ADMIN
Jun 19, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Compute the great-circle distance between two latitude/longitude points using the haversine formula. Returns kilometers; multiply by 0.621 for miles. Useful for "stores near me" features.
PHP
Raw
<?php
function haversineKm(float $lat1, float $lng1, float $lat2, float $lng2): float {
    $R = 6371.0;                       // Earth radius in km
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $a = sin($dLat / 2) ** 2
       + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLng / 2) ** 2;
    return 2 * $R * atan2(sqrt($a), sqrt(1 - $a));
}

// Distance from Austin to San Francisco
printf("%.0f km\n", haversineKm(30.2672, -97.7431, 37.7749, -122.4194));   // ~2425 km
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.