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

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
\$data1 = @file_get_contents(\$pc1);
\$result1 = explode(",", \$data1);
\$custlat1 = \$result1;
\$custlong1 = \$result1;

// Geocode Postcodes & Get Co-ordinates 2nd Postcode
\$data2 = @file_get_contents(\$pc2);
\$result2 = explode(",", \$data2);
\$custlat2 = \$result2;
\$custlong2 = \$result2;

// 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 and \$result2 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 != 200) || (\$result2 != 200)) {
echo "<p>Invalid Postcode(s) Entered. Please try again.</p>";
} else {```

Good luck!