Measuring the distance between two coordinates in PHP

To calculate the distance between two coordinates in PHP, you can use the Haversine formula, which is a formula used to calculate the distance between two points on a sphere based on their longitudes and latitudes. Here is an example of how you can use the Haversine formula to calculate the distance between two coordinates in PHP:

<?php

/**
 * Calculate the Haversine distance between two points on the Earth's surface
 *
 * @param float $lat1 The latitude of the first point
 * @param float $lon1 The longitude of the first point
 * @param float $lat2 The latitude of the second point
 * @param float $lon2 The longitude of the second point
 * @return float The distance between the two points, in kilometers
 */
function haversine_distance($lat1, $lon1, $lat2, $lon2)
{
  $radius = 6371; // Earth's radius in kilometers

  // Calculate the differences in latitude and longitude
  $delta_lat = $lat2 - $lat1;
  $delta_lon = $lon2 - $lon1;

  // Calculate the central angles between the two points
  $alpha = $delta_lat / 2;
  $beta = $delta_lon / 2;

  // Use the Haversine formula to calculate the distance
  $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin(deg2rad($beta)) * sin(deg2rad($beta));
  $c = asin(min(1, sqrt($a)));
  $distance = 2 * $radius * $c;

  // Round the distance to four decimal places
  $distance = round($distance, 4);

  return $distance;
}

// Sample usage
$lat1 = 40.712776;
$lon1 = -74.005974;
$lat2 = 51.507351;
$lon2 = -0.127758;

$distance = haversine_distance($lat1, $lon1, $lat2, $lon2);
echo "The distance between ($lat1, $lon1) and ($lat2, $lon2) is $distance km.";

Watch a course Learn object oriented PHP

This code includes a function haversine_distance that calculates the distance between two points on the Earth's surface using the Haversine formula. The function takes four parameters: the latitude and longitude of the first point, and the latitude and longitude of the second point. The function returns the distance between the two points, in kilometers.

The code also includes a sample usage of the function, which calculates the distance between two cities (New York and London) and outputs the result as a string. The output will look something like this:

The distance between (40.712776, -74.005974) and (51.507351, -0.127758) is 5570.2266 km.