0

I have a little piece of PHP code that uses JSON to get time and distance from google-maps. Its works if i enter the co-ords into the URL but when I load then from variables it doesn't work? What am i doing wrong?

The code is:

<?

$lat1= "52.40860600000001";
$long1= "-1.5499760999999808";
$lat2= "53.7668532";
$long2= "-2.4743857999999364";

$orig = $lat1.",".$long1;
$dest = $lat2.",".$long2;

$new_url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$orig."&destinations=".$dest."&key=AIzaSyC3lhU4E-viZZ_OBths87Gd0Z7eGR-_1yI";

function GetDrivingDistance()
{
    $url = $new_url;
    $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);
}

$dist = GetDrivingDistance();

echo 'Distance: '.$dist['distance'].'
Travel time duration: '.$dist['time'].''; echo $new_url;

?>
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Jules
  • 143
  • 1
  • 1
  • 15

1 Answers1

0

The problem is, $new_url isn't in the scope of GetDrivingDistance. You should modify your function, that you pass the url (or better, pass the lat/lng values)

function GetDrivingDistance($lat1, $long1, $lat2, $long2)
{
    $orig = $lat1.",".$long1;
    $dest = $lat2.",".$long2;
    $url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=".$orig."&destinations=".$dest."&key=AIzaSyC3lhU4E-viZZ_OBths87Gd0Z7eGR-_1yI";

    $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);
}

$lat1= "52.40860600000001";
$long1= "-1.5499760999999808";
$lat2= "53.7668532";
$long2= "-2.4743857999999364";
$dist = GetDrivingDistance($lat1, $long1, $lat2, $long2);
echo 'Distance: <b>'.$dist['distance'].'</b><br>Travel time duration: <b>'.$dist['time'].'</b>';
Philipp
  • 15,377
  • 4
  • 35
  • 52