omkar
omkar

Reputation: 2038

how to get distance between points using latitude and longitude using php?

I am trying to get distance between two location.

Here one location is user input and another location is my store location. I want to show the the distance between there input location to my store location.

To get user location we use form, where user share there zip code and we convert that zip to longitude and latitude. And in my data base i stored the store location and its respective longitude and latitude.

Here in this case can any one help me to get distance.

Thanks

Upvotes: 1

Views: 7380

Answers (1)

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26288

GeoDataSource team develop a very useful function to achieve this:

function distance($lat1, $lon1, $lat2, $lon2, $unit) {

  $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;
  $unit = strtoupper($unit);

  if ($unit == "K") {
    return ($miles * 1.609344);
  } else if ($unit == "N") {
      return ($miles * 0.8684);
    } else {
        return $miles;
      }
}

echo distance(32.9697, -96.80322, 29.46786, -98.53506, "M") . " Miles<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "K") . " Kilometers<br>";
echo distance(32.9697, -96.80322, 29.46786, -98.53506, "N") . " Nautical Miles<br>";

Reference

Upvotes: 5

Related Questions