Skip to content

Instantly share code, notes, and snippets.

@sutandang
Last active August 29, 2015 14:23
Show Gist options
  • Save sutandang/34d14ab3e88f8891e07f to your computer and use it in GitHub Desktop.
Save sutandang/34d14ab3e88f8891e07f to your computer and use it in GitHub Desktop.
get distance from many locations with google maps api v3
/*
$locations = array('longitude,latitude')
*/
function getDistance($locations)
{
$waypoints = $locations;
if(count($waypoints) > 2)
{
unset($waypoints[0]);
unset($waypoints[count($locations) - 1]);
}else{
$waypoints = array();
}
if($waypoints)
{
$waypoints = implode('|', $waypoints)
}
$parameterurl = array(
'origin' => $locations[0],
'destination' => $locations[count($locations) - 1],
'waypoints' => $waypoints,
'sensor' => 'false',
'units' => 'driving'
);
$params_string = '';
foreach($parameterurl as $var => $val){
$params_string .= '&' . $var . '=' . urlencode($val);
}
$url = 'https://maps.googleapis.com/maps/api/directions/json?'.ltrim($params_string, '&');
$response = file_get_contents($url);
$response = json_decode($response);
$data = $response->routes[0]->legs;
if($data)
{
$output = 0;
foreach($data AS $location)
{
$output += $location->distance->value;
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment