Search code examples
phpcurlgeocoding

Google Geocoding API no results with php-CUrl


I have a problem with the Google Geocoding API. When I go to the URL corresponding to the api call I want https://maps.googleapis.com/maps/api/geocode/json?address=6+QUAI+DE+LORIENT+94569+RUNGIS+CEDEX&key=[API_KEY] I have 2 results. When I ask It throught php-CUrl, I have a "No Result" response. On 300 differents addresses, I have a few like it (15 at most). I don't know why.

I tried a few things : classic Curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);

Curl Class (https://github.com/php-curl-class/php-curl-class):

$curl->setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36');
$curl->setHeader('pragma', 'no-cache');
$curl->setHeader('accept-encoding', 'gzip, deflate, sdch');
$curl->setHeader('accept-langage', 'fr-FR,fr;q=0.8,en;q=0.6,en-US;q=0.4');
$curl->setHeader('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8');
$curl->setHeader('cache-control', 'no-cache');
$curl->setHeader('authority', 'maps.googleapis.com');
$curl->get($url);

With and without user-agent/headers.


Solution

  • Independed from CURL or whatever request method is being used, I would suggest always adding a countrycode at the end of the query string so google knows where to look instead of guessing based on parameters / requestheaders.

    Notice the difference between:

    $result = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=6+QUAI+DE+LORIENT+94569+RUNGIS+CEDEX');
    var_dump(json_decode($result));
    
    $result = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=6+QUAI+DE+LORIENT+94569+RUNGIS+CEDEX,FR');
    var_dump(json_decode($result));
    

    First one does not give results, the second one does.