Search code examples
phpgoogle-mapsgoogle-maps-api-3geocodinggoogle-geocoder

Google Map Geocode API returns null


When I try to call Google Maps Geocode API via URL, it works fine and returns the correct JSON.

For example, this is the URL:

https://maps.googleapis.com/maps/api/geocode/json?address=2140+Amphitheatre+Parkway,+Mountain+View,+IN&key=AIzaSyCUDSJ2GBE1DHupbAZT4u8gZqclkIhmb0M

When I try the same with my PHP codes, it returns null.

Below is my code:

<?php
 
function lookup($string){
 
   $string = str_replace (" ", "+", urlencode($string));
   $details_url = "http://maps.googleapis.com/maps/api/geocode/json?address=".$string."&sensor=false";
 
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $details_url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $response = json_decode(curl_exec($ch), true);
 
   // If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
   if ($response['status'] != 'OK') {
    return null;
   }
 
   print_r($response);
   $geometry = $response['results'][0]['geometry'];
 
    $longitude = $geometry['location']['lat'];
    $latitude = $geometry['location']['lng'];
 
    $array = array(
        'latitude' => $geometry['location']['lng'],
        'longitude' => $geometry['location']['lat'],
        'location_type' => $geometry['location_type'],
    );
 
    return $array;
 
}
 
$city = 'San Francisco, USA';
 
$array = lookup($city);
var_dump($array);
 
?>
</pre>

I tried adding and removing the API key but it's still returning null.

Appreciate any support.


Solution

  • It seems code is fine and it is working well, You just need to check that curl is enabled or not. I think this is the reason that you can not get data with php.