Google Maps Distance (DistanceMatrix) API for UK in JSON

The postcode code has been updated to use Google’s distancematrix api, which provides a very different set of data from the old “as the bird flies” calculation (it calculates road distance, and provides transport options etc).

The following code is merely a demonstration, which can be seen here.

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

// Set and retrieve the query URL
$request = "" . $postcode1 . "&destinations=" . $postcode2 . "&mode=driving&language=en-GB&sensor=false&units=imperial";
$distdata = file_get_contents($request);

// Put the data into an array for easy access
$distances = json_decode($distdata, true);

// Do some error checking, first for if the response is ok
$status = $distances["status"];
$row_status = $distances["rows"][0]["elements"][0]["status"];

if ($status == "OK" && $row_status == "OK") {

// Calculate the distance in miles
$distance = $distances["rows"][0]["elements"][0]["distance"]["value"];
$distance_miles = round($distance * 0.621371192/1000, 2);

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

} else {
    echo "Calculating the distance between your locations caused an error.";


Having better error checking would also be a good idea if you plan to use the above code. Using &unit=imperial is optional, as Google always returns metres – so the code runs a basic calculation on these to convert to miles.

One thought on “Google Maps Distance (DistanceMatrix) API for UK in JSON”

Comments are closed.