Using Google Maps, Geocoding and PHP to find the distance between UK Postcodes

August 25, 2010

UPDATE: A new version which calculates distance based on roads is available.

If you're looking to make any kind of radius checker, delivery calculator etc, you will need to have some method of calculating this distance. Unfortunately for us in the UK, Royal Mail keep a tight grip on postcode data.

As a result, the best low-budget way of finding postcodes is by using the Google Maps api - which in itself isn't 100% accurate (but good enough).

So we can use the following code:

<?php
// Specify Postcodes to Geocode
$postcode1 = 'BH151DA';
$postcode2 = 'BH213AP';

// Geocode Postcodes & Get Co-ordinates 1st Postcode
$pc1 = 'http://maps.google.com/maps/geo?q='.$postcode1.',+UK&output=csv&sensor=false';
$data1 = @file_get_contents($pc1);
$result1 = explode(",", $data1);
$custlat1 = $result1[2];
$custlong1 = $result1[3];

// Geocode Postcodes & Get Co-ordinates 2nd Postcode
$pc2 = 'http://maps.google.com/maps/geo?q='.$postcode2.',+UK&output=csv&sensor=false';
$data2 = @file_get_contents($pc2);
$result2 = explode(",", $data2);
$custlat2 = $result2[2];
$custlong2 = $result2[3];

// Work out the distance!
$pi80 = M_PI / 180;
$custlat1 *= $pi80;
$custlong1 *= $pi80;
$custlat2 *= $pi80;
$custlong2 *= $pi80;

$r = 6372.797; // mean radius of Earth in km
$dlat = $custlat2 - $custlat1;
$dlng = $custlong2 - $custlong1;
$a = sin($dlat / 2) * sin($dlat / 2) + cos($custlat1) * cos($custlat2) * sin($dlng / 2) * sin($dlng / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));

// Distance in KM
$km = round($r * $c, 2);

// Distance in Miles
$miles = round($km * 0.621371192, 2);

echo 'The distance between '.$postcode1.' and '.$postcode2.' is '.$km.'Km ('.$miles.' miles).';

?>

You could use $result1[0] and $result2[0] to check codes. If the value is anything other than 200 the postcode is invalid. Also note UK is also searched for to guarantee correct results!

The result is also rounded to make sure we only have 2 decimal places. Make sure your postcodes do not have any spaces in when they go to Google, if you're collecting them from a form maybe use:

function nowhitespace($data) {
  return preg_replace('/\s/', '', $data);
}
$postcode1 = nowhitespace($postcode1);

to remove all spaces before processing, and the following to check it's ok after processing:

if (($result1[0] != 200) || ($result2[0] != 200)) {
  echo "<p>Invalid Postcode(s) Entered. Please try again.</p>";
} else {

Good luck!


Profile picture

From Dave, who writes to learn things. Thoughts and views are his own.

© 2024, withdave.