How can PHP be used to calculate distances between coordinates stored in MySQL tables?
To calculate distances between coordinates stored in MySQL tables using PHP, you can utilize the Haversine formula. This formula calculates the distance between two points on the Earth given their latitude and longitude coordinates. By querying the MySQL database for the coordinates of the two points, you can then use the Haversine formula in your PHP code to calculate the distance between them.
// Function to calculate the distance between two sets of coordinates using the Haversine formula
function calculateDistance($lat1, $lon1, $lat2, $lon2) {
$earthRadius = 6371; // Earth's radius in kilometers
$dLat = deg2rad($lat2 - $lat1);
$dLon = deg2rad($lon2 - $lon1);
$a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
$c = 2 * atan2(sqrt($a), sqrt(1-$a));
$distance = $earthRadius * $c;
return $distance;
}
// Query the MySQL database to get the coordinates of the two points
$point1 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT lat, lon FROM coordinates WHERE id = 1"));
$point2 = mysqli_fetch_assoc(mysqli_query($conn, "SELECT lat, lon FROM coordinates WHERE id = 2"));
// Calculate the distance between the two points
$distance = calculateDistance($point1['lat'], $point1['lon'], $point2['lat'], $point2['lon']);
echo "The distance between the two points is: " . $distance . " kilometers";