Goran Goran - 29 days ago 15
PHP Question

php - Get driving distance between two points using Google Maps API and calculate time

How to display time example 16:00 any have idea how to make this?

function GetDrivingDistance($lat1, $lat2, $long1, $long2)
{
$url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=".$lat1.",".$long1."&destinations=".$lat2.",".$long2."&mode=driving&language=de";
$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);
}
//$pickuplocation = 'Herbststrasse 5';
//$droplocation = 'Pastorstrasse 5';
$coordinates1 = get_coordinates('wien', 'Stefan Esders Platz 1', '');
$coordinates2 = get_coordinates('wien', 'Pastorstrasse 1', '');
if ( !$coordinates1 || !$coordinates2 )
{
echo 'Bad address.';
}
else
{
$dist = GetDrivingDistance($coordinates1['lat'], $coordinates2['lat'], $coordinates1['long'], $coordinates2['long']);
echo 'Entfernung: <b>'.$dist['distance'].'</b><br>Fahrzeit: <b>'.$dist['time'].'</b>';
}
?>



Entfernung: 662 km Fahrzeit: 6 Stunden, 56 Minuten


I need to display time example 6:56 any can help?

Answer

Instead of getting the 'text' field from the response:

$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['text'];

Try the value:

$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];
$time = $response_a['rows'][0]['elements'][0]['duration']['value'];

That is the total number of seconds, do your math on it and you can format it as you please.

$hours = floor($time / 3600);
$mins = floor($time / 60 % 60);
$secs = floor($time % 60);
Comments