BHUY3467789
BHUY3467789

Reputation: 3

Google reverse Geocode return null

I'm currently using this function to reverse geocode latlng from instagram pictures:

 function getGeoCountry($geoAddress) {
    $url = 'http://maps.google.com/maps/api/geocode/json?address=' . $geoAddress .'&sensor=false'; 
    //$get     = file_get_contents($url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    $geoData = json_decode($response);
    if(isset($geoData->results[0])) {
        foreach($geoData->results[0]->address_components as $addressComponent) {
            if(in_array('country', $addressComponent->types)) {
                return array($addressComponent->short_name, $addressComponent->long_name); 
            }
        }
    }
    return null; 
}

This works like 60% of the time but returns null sometimes. Basicly I have no idea what causes this and I need someone to help me get through the problem.

Thanks in advance

Upvotes: 0

Views: 597

Answers (1)

Dr.Molle
Dr.Molle

Reputation: 117354

  1. it's not clear what $geoAddress is, but when it's not urlencoded yet you must encode it:

    $url = 'http://maps.google.com/maps/api/geocode/json?address=' .
              urlencode($geoAddress);
    
  2. use a key to be sure that you don't share the request-quota with other domains hosted on the same server

  3. be sure that you don't run this function more than 10 times per second

  4. geocoding may fail, we need to see a example-response for a failing attempt to isolate the issue

Upvotes: 1

Related Questions