Skip to content

Instantly share code, notes, and snippets.

@o-shabashov
Created May 29, 2016 22:45
Show Gist options
  • Save o-shabashov/701f1f05fd022cb348dfa008fbcbc185 to your computer and use it in GitHub Desktop.
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
<?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