Search code examples
phparraysjsongoogle-mapsgoogle-geolocation

Getting response from GOOGLE MAPS GEOLOCATION API in PHP, the output is in JSON


I have been looking for answers everywhere, didn't find one. I am using google map geolocation api to display Address from Lat,Long. I need to display only selective data like: "formatted_address" from array. This is the code which I have tried to display response in PHP:

$file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

foreach($data as $output => $var) {
    echo $var;
}

This is the response: [https://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875]

This is the output I get:

Notice: Array to string conversion in C:\xampp\htdocs\bikewala\myaccount\index.php on line 176
ArrayOK

When I try to access any component of array using this code:

$file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=31.334097,74.235875&sensor=false", true);
$data = json_decode($file_contents, true);

foreach($data as $output => $var) {
    echo $var['formatted_address'];
}

I get this error:

Notice: Undefined index: formatted_address in C:\xampp\htdocs\bikewala\myaccount\index.php on line 176

Warning: Illegal string offset 'formatted_address' in C:\xampp\htdocs\bikewala\myaccount\index.php on line 176
O

What am I doing wrong here?

Thanks in advance!


Solution

  • instead of echo (in your first code section) use print_r($var)

    $file_contents = 
    file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?
    latlng=31.334097,74.235875&sensor=false", true);
    $data = json_decode($file_contents, true);
    
    foreach($data as $output => $var) {
       print_r($var);
    }
    

    this will allow you to see the path to the value you are wanting

    You can access the exact value you are wanting with this code

    $file_contents = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?
    latlng=31.334097,74.235875&sensor=false", true);
    $data = json_decode($file_contents, true);
    
    $formatted_address = $data['results']['0']['formatted_address'];
    echo $formatted_address;