0
votes

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.

1
Did you include everything you need to have? + turn on error reporting? Maybe you are gtting an error or something?Naruto
Its working fine i have checked it on my localhost and works. I am getting this array(3) { ["latitude"]=> float(-122.4194155) ["longitude"]=> float(37.7749295) ["location_type"]=> string(11) "APPROXIMATE"Vivek
I am confused, why it don't return me anythingdev1234
@Vivek can you post your code pleasedev1234
It's not really an answer to your question, but how about getting the data via javascript, then upload the data to the server?Emmanuel Delay

1 Answers

0
votes

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.