PHP curl google maps api返回零结果,而浏览器返回相同的url

时间:2018-02-23 15:37:42

标签: php google-maps curl

我正在制作一个php curl请求但是正如标题所说它返回零结果而在浏览器中它给出结果,其他zipcodes给出了curl和浏览器的结果。 (我取出了api键,因此它可以在这里测试,但是api键也是如此,所以我没有得到你已经超出了你的每日请求但只是空数组)。

在浏览器中尝试以下网址,并在https://onlinecurl.com/

中调用curl
https://maps.googleapis.com/maps/api/geocode/json?address=4735CC,,&componentRestrictions=country:NL&sensor=false

完整代码:

gives result browser but not in curl
          //https://maps.googleapis.com/maps/api/geocode/json?address=4735CC,,&componentRestrictions=country:NL&sensor=false

gives result in curl & browser
        //https://maps.googleapis.com/maps/api/geocode/json?address=4751AJ,,&componentRestrictions=country:NL&sensor=false


            function getCoordinates($address, $zipcode, $city) {
                $location       = urlencode($address).','.urlencode($zipcode).','.urlencode($city);
                $details_url    = "https://maps.googleapis.com/maps/api/geocode/json?address=".$location;
                usleep(500000);

                $ch = curl_init();
                curl_setopt($ch, CURLOPT_HTTPGET,true);
                curl_setopt($ch, CURLOPT_URL, $details_url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                $response   = json_decode(curl_exec($ch), true);
                var_dump($response);
 // gives {
   "results" : [],
   "status" : "ZERO_RESULTS"
}

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的意见!尝试此代码,如果您只设置地址/邮政编码/城市,那么它将起作用。可能是谷歌地图无法找到您的输入地址+邮政编码+城市的组合。

    function getCoordinates($address, $zipcode = null, $city = null ) {
        // $location       = urlencode($address).','.urlencode($zipcode).','.urlencode($city);
       $location = urlencode($address);
        $details_url    = "https://maps.googleapis.com/maps/api/geocode/json?key=key&address=".$location;
        usleep(500000);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPGET,true);
        curl_setopt($ch, CURLOPT_URL, $details_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response   = json_decode(curl_exec($ch), true);
        var_dump($response); }