<?php
$address = "alaba rago bus stop, Lagos";

$url = "https://maps.google.com/maps/api/geocode/json?key=AIzaSyCVpBowbdZqwo-eMCbY_lVhhuQj5aUn3Tk&address=".urlencode($address);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);    
$responseJson = curl_exec($ch);
curl_close($ch);

$response = json_decode($responseJson);

//if ($response->status == 'OK') {
    $latitude = $response->results[0]->geometry->location->lat;
    $longitude = $response->results[0]->geometry->location->lng;
    
    
$geolocation = $latitude.','.$longitude;
$request = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='.$geolocation.'&sensor=false&key=AIzaSyCVpBowbdZqwo-eMCbY_lVhhuQj5aUn3Tk'; 
$file_contents = file_get_contents($request);
$json_decode = json_decode($file_contents);
if(isset($json_decode->results[0])) {
    $response = array();
    foreach($json_decode->results[0]->address_components as $addressComponet) {
        if(in_array('political', $addressComponet->types)) {
                $response[] = $addressComponet->long_name; 
        }
    }

    if(isset($response[0])){ $first  =  $response[0];  } else { $first  = 'null'; }
    if(isset($response[1])){ $second =  $response[1];  } else { $second = 'null'; } 
    if(isset($response[2])){ $third  =  $response[2];  } else { $third  = 'null'; }
    if(isset($response[3])){ $fourth =  $response[3];  } else { $fourth = 'null'; }
    if(isset($response[4])){ $fifth  =  $response[4];  } else { $fifth  = 'null'; }
    if(isset($response[4])){ $six  =  $response[5];  } else { $six  = 'null'; }

    $town = $first;
}
    echo 'Latitude: ' . $latitude;
   echo '<br />';
    echo 'Longitude: ' . $longitude;
   echo '<br />';
    echo 'Town: ' . $town;
    

/*} else {
    echo $response->status;
    var_dump($response); 
}    */
?>
