find the distance between two points in php

To find the distance between two points in PHP, you can use the distance formula from geometry.

Here's an example code snippet:

main.php
function distance($lat1, $lon1, $lat2, $lon2) {
  $theta = $lon1 - $lon2; 
  $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta)); 
  $dist = acos($dist); 
  $dist = rad2deg($dist); 
  $miles = $dist * 60 * 1.1515;
  return $miles;
}

$distance = distance(40.7128, -74.0060,  37.7749, -122.4194);
echo "The distance between the two points is " . $distance . " miles.";
434 chars
12 lines

In this example, the distance() function takes four parameters: the latitude and longitude of the two points. The function then calculates the distance using the Haversine formula, which takes into account the curvature of the earth.

Finally, the code calculates the distance in miles and returns the result.

gistlibby LogSnag