Calculating distance between two postcodes with PHP

2011-04-21

Distance between two postcodes

If you are looking for a quick check between two postcodes, our online distance calculator can help.

If you are interested in some scripts which can help parts of your program, below is how to perform distance calculation with PHP.

The distance between two postcodes refers to the the great-circle distance, the shortest distance between them, not the route distance by transport. Since postcode itself doesn't give any geographic information, we need to convert each postcode to its coordinate value - latitude and longitude. If you don't know how to do it, here we have a free online tool to convert postcodes to latitude and longitude.

PHP function

function postcodes_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;
 
  switch ($unit)
  {
  	// kilometers;
  	case "k": $distance = $miles * 1.609344; break;
  	// nautical miles;
  	case "n": $distance = $miles * 0.8684; break;
  	// meters;
  	case "m": $distance = $miles * 1609.344; break;
  	// feet;
  	case "f": $distance = $miles * 5280; break;
  	// yards;
  	case "y": $distance = $miles * 1760; break;
  	default: $distance = $miles; break;
  }
  return $distance;
}

Download

Click to download above scripts (536 bytes).