Get street,town and country from google api

In this tutorial, I am going to show you how to get street,town and country values of given postal code.

$postcode = "your postal code goes here";

// Sanitize their postcode:
$search_code = urlencode($postcode);
$url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' . $search_code . '&sensor=false';
$json = json_decode(file_get_contents($url));



$lat = $json->results[0]->geometry->location->lat;
$lng = $json->results[0]->geometry->location->lng;



echo "Latitude :".$lat ;
echo "Longitude :".  $lng ;



// Now build the lookup:
$address_url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' . $lat . ',' . $lng . '&sensor=false';
$address_json = json_decode(file_get_contents($address_url));
$address_data = $address_json->results[0]->address_components;


$street = str_replace('Dr', 'Drive', $address_data[1]->long_name);
$town = $address_data[2]->long_name;
$county = $address_data[3]->long_name;



$array = array('street' => $street, 'town' => $town, 'county' => $county);
echo json_encode($array);
?>

I have entered "45 Belsize Avenue, London, NW3 4BN" as $postcode and I could get below output.

$postcode = "45 Belsize Avenue, London, NW3 4BN";


Have Something to clear ? Drop me a comment or drop me a email. !!!
etutionlk@gmail.com

0 comments:

Post a Comment

Ask anything about this Tutorial.