Google Maps Distance (DistanceMatrix) API for UK in JSON

November 11, 2013

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 demonstrates this:

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

// Set and retrieve the query URL
$request = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" . $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.


Profile picture

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

© 2024, withdave.