Jump to content

Calculate Distance Between Decimal Co-ordinates


maxudaskin

Recommended Posts

Table Of Contents

- General Description

- Database Image

- Code

- Code

- Issue

 

I have the following code (from outside sources), which, is apparently incompatible with my co-ordinate types.

 

Here is a database excerpt (first thirty rows) of about 9200 airports from around the world.

db.JPG

<?php
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;
      }
}
$dep = $_GET['dep'];
$arr = $_GET['arr'];

$sql   = 'SELECT * FROM `airports` WHERE `iata` = \'' . $dep . '\'';
$query = mysql_query($sql);
$dep   = mysql_fetch_array($query);

$sql   = 'SELECT * FROM `airports` WHERE `iata` = \'' . $arr . '\'';
$query = mysql_query($sql);
$arr   = mysql_fetch_array($query);

echo distance($dep['latt'], $dep['long'], $arr['latt'], $arr['latt'], "k") . " km<br>";
?>

 

Here is my output [dep=yyz, arr=yul] with [yyz = 43.68, -79.63; yul = 45.47, -73.74] : 8719.64724823 km

 

Obviously, with YYZ being Toronto, Canada and YUL being Montreal, Canada, it is definitely not 9000 km away (actually, ~500 km).

 

Can you help me convert the units, or re-write the algorithms in order to make it function correctly.

 

Thank you in advance.

I didn't pay attention to the build of your function, thought it was your own.

 

Here is what I used on my test server. 

 

Function posted above

<?php
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;
      }
}

//hard coded your lat/lon into the function arguments.
echo distance(43.68,-79.63,45.47,-73.74,'M') . ' Miles from Toronto to Montreal, Canada.';
echo distance(43.68,-79.63,45.47,-73.74,'K') . ' Kilometers from Toronto to Montreal, Canada.';
?>

 

Output

315.055202461 Miles from Toronto to Montreal, Canada.

507.032199749 Kilometers from Toronto to Montreal, Canada.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.