Search code examples
phpmysqljsonfile-get-contentsgeocode

How to convert Lat Long to address in php with json api?


This is my code to get address off particular lat long dynamically from db.If i used this static value it works fine. but if i used $latlong this variable to get dynamic values. it shows error. what's the solution for this. please help me with the same.

Notice: Undefined offset: 0 in C:\xampp\htdocs\demo_calLatLong\calLatLong.php on line 21 Notice: Trying to get property of non-object in C:\xampp\htdocs\demo_calLatLong\calLatLong.php on line 21

<table class="table table-bordered">
        <thead>
            <tr>         
              <th>Client Name</th>                                            
            </tr>
        </thead>
        <?php 
            include 'db.php';
            $sql = 'SELECT  *  FROM `location`';            
            $travel = mysqli_query($conn,$sql);     
        while ($row = mysqli_fetch_array($travel)) 
        {?>         
        <tbody>
            <tr class="active">
            <?php
               $latlong = $row[1].','.$row[2];
               $geocode=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=19.0978,22.8972&sensor=false',true));            
            ?>  
            <td><?php echo $geocode->results[0]->formatted_address;?></td>                                
            </tr>                               
        </tbody>
    <?php }?>
    </table>

Solution

  • You are trying to access url not a file, Use CURL instead to access file direct.

    Replace

            <?php
               $latlong = $row[1].','.$row[2];
               $geocode=json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=19.0978,22.8972&sensor=false',true));            
            ?> 
    

    To

    <?php
        $url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$row[1],$row[2]&sensor=false";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        $geocode = json_decode($output);
    ?>