Created
May 29, 2016 22:45
-
-
Save o-shabashov/701f1f05fd022cb348dfa008fbcbc185 to your computer and use it in GitHub Desktop.
Google Maps API Calculating route to the coordinates or name, return travel time and distance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class DistanceHelper { | |
/** | |
* @param string | float $from | |
* @param string | float $to | |
* | |
* @return object | |
*/ | |
public static function calculate($from, $to) { | |
$from = urlencode($from); | |
$to = urlencode($to); | |
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false"); | |
$data = json_decode($data); | |
$time = 0; | |
$distance = 0; | |
foreach ($data->rows[0]->elements as $road) { | |
$time += $road->duration->value; | |
$distance += $road->distance->value; | |
} | |
return (object)array( | |
'seconds' => $time, | |
'meters' => $distance, | |
'miles' => $distance / 1609.344 | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment