Using Google Directions API

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

[code]

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 = ‘http://maps.googleapis.com/maps/api/directions/json?’;
$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 ‘

Directions

‘;
echo ‘

From: ‘.$params[‘origin’].’ to: ‘.$params[‘destination’];
$copy=explode(‘©’,$route->copyrights);
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)
{
$no=1;
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
$no++;
}
}

}//end of parse data

}//end of function

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

Directions

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)

Leave a Reply

Your email address will not be published. Required fields are marked *