Question

I'm trying to get the formatted address from this URL. I have tried this below coding. But it doesn't display anything and doesn't show any error too.. How do I get the formatted address from json decode result?

 while($r = mysql_fetch_assoc($res)) {

                $lat = $r['latitude'];
                $lng = $r['longitude'];

                $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
                $jsons = @file_get_contents($url);
                $data = json_decode($jsons,true);
                echo $data->results[0]->formatted_address;

                $json[]= array("nod"=>ucwords($r['driver_name']),"info"=>ucwords($r['driver_name'])."<br />Speed:<b>".$r['current_speed']."Km/h</b>","lat"=>$r['latitude'],"lng" => $r['longitude'],"location"=> $data, "did"=>$r['driver_id'],"mobile_number"=>$r['mobile_number'],"current_speed"=>$r['current_speed']." km/h","vehicle_name"=>$r['vehicle_name'],"vehicle_number"=>$r['registration_number']);

                }
Was it helpful?

Solution

Here you go :

<?php
while($r = mysql_fetch_assoc($res)) {
    $lat = urlencode(trim($r['latitude']));
    $lng = urlencode(trim($r['longitude']));

    $url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$lng.'&sensor=false';
    $jsons = @file_get_contents($url);
    $data = json_decode($jsons,true);

    $address = $data['results'][0]['formatted_address'];

    $json [] = array(
        "nod" => ucwords($r['driver_name']),
        "info" => ucwords($r['driver_name'])."<br />Speed:<b>".$r['current_speed']."Km/h</b>",
        "lat" => $r['latitude'],
        "lng" => $r['longitude'],
        "location" => $address,
        "did" => $r['driver_id'],
        "mobile_number" => $r['mobile_number'],
        "current_speed" => $r['current_speed']." km/h",
        "vehicle_name" => $r['vehicle_name'],
        "vehicle_number" => $r['registration_number']
    );
}
?>

OTHER TIPS

Try this, it should be $data instead of $datas

 $data=json_decode($jsons);
 echo $data->results[0]->formatted_address;

instead of

$data=json_decode($jsons);
$datas->results[0]->formatted_address;
   --^

I got the output for

$lat = 32;
$lng = 40;
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.trim($lat).','.trim($lng).'&sensor=false';
$jsons = @file_get_contents($url);

$data=json_decode($jsons);
echo $data->results[0]->formatted_address; // output: 75898, Saudi Arabia
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top