Last active
August 29, 2015 14:23
-
-
Save sutandang/34d14ab3e88f8891e07f to your computer and use it in GitHub Desktop.
get distance from many locations with google maps api v3
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
/* | |
$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