【问题标题】:Making a call to Google maps API's but getting empty response调用 Google 地图 API 但得到空响应
【发布时间】:2017-04-24 23:59:32
【问题描述】:

我正在尝试通过 Laravel 5.3 中的 cURL 与 Google 进行通信。 我得到一个空的响应,但是一个 200 状态码。 这是我的代码:

    public function directionGet($origin, $destination) {
    $callToGoogle = curl_init();
    $googleApiKey = '**************************';

    curl_setopt_array(
      $callToGoogle,
      array (
          CURLOPT_URL => 'http://maps.googleapis.com/maps/api/directions/json?origin='. $origin.'&destination=' . $destination . '&key= ' . $googleApiKey,
          CURLOPT_POST => true,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HEADER => 0
        )
    );
    $response = curl_exec($callToGoogle);
    curl_close($callToGoogle);
    return response()->json($response); 
}

【问题讨论】:

标签: php laravel api curl


【解决方案1】:

我在您的代码中发现了一些问题 1. 我认为 google 要求你使用 https 而不是 http 以确保安全 2. $origin 和 $destination 需要在 curl 发送前对 url 格式进行编码 3. $key后面有1个空格

所以你试试这个代码

public function directionGet($origin, $destination) {

    $googleApiKey = '****************************';

    $url          = 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey;

    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL            => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_MAXREDIRS      => 10,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST  => "GET",
        CURLOPT_HTTPHEADER     => [
            "cache-control: no-cache"
        ],
    ]);

    $response = curl_exec($curl);

    return $response; 
}

$origin = "75 9th Ave, New York, NY";
$destination = "MetLife Stadium Dr East Rutherford, NJ 07073";

$directions = directionGet($origin, $destination);

你问我你的代码有什么问题 答案是 1.我把http改成https 2.我添加修改你的标题(删除帖子标题,因为它使用get方法) 3.我用url格式编码字符串(urlencode)

例如我修改你的代码

function directionGet($origin, $destination) {
    $callToGoogle = curl_init();
    $googleApiKey = '*************************';

    curl_setopt_array(
      $callToGoogle,
      array (
          CURLOPT_URL => 'https://maps.googleapis.com/maps/api/directions/json?origin='. urlencode($origin).'&destination=' . urlencode($destination) . '&mode=driving&key=' . $googleApiKey,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_RETURNTRANSFER => true,
        )
    );
    $response = curl_exec($callToGoogle);
    curl_close($callToGoogle);
    return $response; 
}

希望有帮助

【讨论】:

  • 成功了!我做错了什么?我是 cURL 的新手,所以我很乐意学习
  • 我在旧帖子中添加了答案
猜你喜欢
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 2015-06-03
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2022-08-05
  • 1970-01-01
相关资源
最近更新 更多