Php 调用谷歌地图API';但是得到的是空洞的回应

Php 调用谷歌地图API';但是得到的是空洞的回应,php,laravel,api,curl,Php,Laravel,Api,Curl,我正试图在Laravel5.3中与Google交流。 我得到一个空响应,但状态码是200。 这是我的密码: public function directionGet($origin, $destination) { $callToGoogle = curl_init(); $googleApiKey = '**************************'; curl_setopt_array( $callToGoogle, arra

我正试图在Laravel5.3中与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); 
}

我在你的代码中发现了一些问题 1.我认为谷歌要求你使用https而不是http来保证安全 2. $在发送之前,源和$destination需要对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; 
}

希望获得此帮助

您确定您的google map api密钥也在您的google dev仪表板中配置了吗?我可以推荐使用guzzle,因为它非常易于使用和阅读;)成功了!我做错了什么?我是旋度新手,所以我很乐意学习我在旧帖子中添加答案