Using Google Directions API

  |   By  |  0 Comments

It took some boiling down, but here’s how to grab directions from Google and display them using PHP


function google_directions($start,$end,$mode=’driving’,$units=’imperial’,$region)
$start is the start address
$end is the end address
$mode can be ddriving,walking or bicycling
$units can be metric or imperial
$region biases the address geolocation to a region – use top level domain letters eg uk for GB!


$endpoint = ‘’;
$params = array(
‘origin’ => $start,
‘destination’ => $end,
‘mode’ => $mode,
‘sensor’ => ‘false’,
‘units’ =>$units,
‘region’ =>$region

// Fetch and decode JSON string into a PHP object
$json = file_get_contents($endpoint.http_build_query($params));
$data = json_decode($json);
// If we got directions, output all of the HTML instructions
if ($data->status === ‘OK’)
{//parse google data
$route = $data->routes[0];
echo ‘


echo ‘

From: ‘.$params[‘origin’].’ to: ‘.$params[‘destination’];
echo ‘ using Google Maps ©’.$copy[‘1′].’
echo ‘Journey Distance ‘.$route->legs[0]->distance->text.’
echo ‘Journey Time ‘.$route->legs[0]->duration->text.’

//output warnings
foreach($route->warnings AS $key=>$value)echo $value.’
//start to output directions
echo ‘

Route Summary ‘.$route->summary.’


foreach ($route->legs as $leg)
foreach ($leg->steps as $step)
$text=$step->html_instructions .’ (‘. $step->distance->text.’ and ‘.$step->duration->text.’)’;

$text=strip_tags($text);//get rid of formatting
$text=str_replace(‘Continue’, ‘ & continue ‘ ,$text);
$text=str_replace(‘Go’, ‘ & go ‘ ,$text);
echo $no.’) ‘.$text.’
‘;//o/p step

}//end of parse data

}//end of function

google_directions(‘PE35 6EN’,’PE30 4AW’,’driving’,’imperial’,’uk’);
My example gives the directions from the Sandringham Royal Estate to our church venue, just in case the Queen needs them next Christmas!


From: PE35 6EN to: PE30 4AW using Google Maps ©2011 Tele Atlas
Journey Distance 7.2 mi
Journey Time 16 mins

Route Summary Queen Elizabeth Way/A149

1) Head southwest (0.5 mi and 2 mins)
2) Turn right onto B1439 (1.6 mi and 3 mins)
3) Turn left onto Queen Elizabeth Way/A149 & go through 1 roundabout (4.1 mi and 7 mins)
4) At the roundabout, take the 3rd exit onto Gayton Rd/A1076 (0.8 mi and 2 mins)
5) Turn right onto Queensway
Destination will be on the right (0.2 mi and 2 mins)



Andy Moyle is a church leader and web developer. His biggest project is the Church Admin WordPress plugin and app. He also runs, mainly so he can eat pizza.