Curl with Google Maps Directions API returning null

Asked

Viewed 402 times

1

Below is the code I’m using:

          $arquivo = "destino.json";
          $info = file_get_contents($arquivo);
          $lendo = json_decode($info);

          foreach($lendo->rotas as $campo){

            echo "<b>Origem:</b> ".$campo->origem;
            $origin = $campo->origem;
            echo "<br /><b>Destino:</b> ".$campo->destino;
            $destination = $campo->destino;

          }

          $key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
          //echo "<br><a href='".$url."' >Calcular Rota</a>";

          $url = "https://maps.googleapis.com/maps/api/directions/json?origin=$origin&destination=$destination&sensor=false&key=$key";

          echo "<br><a href='".$url."'>URL</a>";
          // create curl resource
          $ch = curl_init();
          // set url
          curl_setopt($ch, CURLOPT_URL, $url);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          $output = curl_exec($ch);
          curl_close($ch);

          $arr = json_decode($output, TRUE);

          echo "<br><br><br>";
          echo "";
          print_r($arr);

1 answer

1


The Google Maps API uses HTTPS, add logo on cURL the following:

      curl_setopt($ch, CURLOPT_TIMEOUT, 5);
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);

In addition, the address passed cannot contain spaces, so:

  $origin = str_replace(" ", "", $campo->origem);
  $destination = str_replace(" ", "", $campo->destino

Browser other questions tagged

You are not signed in. Login or sign up in order to post.