Google Maps : Get Driving Distance through API
Background
I have a home automation system at home (you know that from the Yamaha article) and I would like to know the travel time while having breakfast. Always good to plan ahead for any hiccup on the road. Easy to get this info on Google map, but you need a browser and a few clicks, I would like something automated !
API, yes again :)
Google allows API call to any of there platform, but you need a Google developer/cloud account. It has a cost, but if you can maintain the query/month low, it won't be charged.
The first step is to get a API Key. Go to https://console.cloud.google.com/ and create/login to your account and locate the API library, enable Maps JavaScript API. Go to API & Services and locate the credentials section. Create a new API key and allow the following APIs :
The last action on the Google Cloud Console is to copy the KEY on the screen above in the API Key field. This is how you are going to authenticate on each API call.
Let's Php
I'm using 2 functions to get the travel time :
function gMapGetCoordinates($city, $street, $province, $key)
// --------------------------------------------------------------
// Function converting physical address into lat/long coordinates
// --------------------------------------------------------------
function gMapGetCoordinates($city, $street, $province, $key)
{
$address = urlencode($city.','.$street.','.$province);
$url = "https://maps.google.com/maps/api/geocode/json?address=$address&sensor=false®ion=Belgium&key=".$key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response);
$status = $response_a->status;
if ($status == 'ZERO_RESULTS')
{
return FALSE;
}
else
{
$result=array(
'lat' => $response_a->results[0]->geometry->location->lat,
'long' => $long = $response_a->results[0]->geometry->location->lng
); $return = $result;
return $return;
}
}
function gMapGetDrivingDistance($lat1, $lat2, $long1, $long2, $key)
// -----------------------------------------------------------------
// Function returning driving distance between 2 sets of coordinates
// -----------------------------------------------------------------
function gMapGetDrivingDistance($lat1, $lat2, $long1, $long2, $key)
{
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",";
$url.=$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=en-GB&key=".$key;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_a = json_decode($response, true);
$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];
return array('distance' => $dist, 'time' => $time);
}
Then, as easy as it gets, the main program body will be similar to this :
// ==================================================================
// Main entry point
// ==================================================================
// Define start and end point
$myHome= ['city' => "Cerfontaine", 'street' => "", 'state' => "Namur"];
$myWork= ['city' => "Gosselies", 'street' => "Avenue Jean Mermoz", 'state' => "Namur"];
$coordinates1 = gMapGetCoordinates($myHome["city"], $myHome["street"], $myHome["state"],$key);
$coordinates2 = gMapGetCoordinates($myWork["city"], $myWork["street"], $myWork["state"],$key);
if ( !$coordinates1 || !$coordinates2 )
{
echo 'Bad address.';
}
else
{
$dist = gMapGetDrivingDistance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long'],$key);
print("With Current traffic conditions, travel to Fred's work is ".$dist['time']." (for ".$dist['distance'].")\n");
}
The result of the above is :
Now, you can easily fine tune the program to have the result sent to a file or any system that can read it. On my side I will try to integrate it into my Domoticz platform so I will see the result every week-days in the morning on a tablet mounted in the kitchen wall ;)
There are many other API endpoints available for Google Maps, the reference can be found here.
I hope this help !
Comments
Post a Comment
Thank you for your message, it has been sent to the moderator for review...