Many times we are needed to extracting zipcode from address in our project. Using Google Maps API and PHP we can easily get zipcode from address. We had created a simple PHP script for getting zipcode from address.
getZipcode()
function accept one parameter ($address
), into the $address
you need to provide the full address from where you want to get zipcode.
getZipcode()
function is given below:
/**
*
* Author: CodexWorld
* Author URI: http://www.codexworld.com
* Function Name: getZipcode()
* $address => Full address.
*
**/function getZipcode($address){
if(!empty($address)){
//Formatted address
$formattedAddr = str_replace(' ','+',$address);
//Send request and receive json data by address
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false');
$output1 = json_decode($geocodeFromAddr);
//Get latitude and longitute from json data
$latitude = $output1->results[0]->geometry->location->lat;
$longitude = $output1->results[0]->geometry->location->lng;
//Send request and receive json data by latitude longitute
$geocodeFromLatlon = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$latitude.','.$longitude.'&sensor=true_or_false');
$output2 = json_decode($geocodeFromLatlon);
if(!empty($output2)){
$addressComponents = $output2->results[0]->address_components;
foreach($addressComponents as $addrComp){
if($addrComp->types[0] == 'postal_code'){
//Return the zipcode
return $addrComp->long_name;
}
}
return false;
}else{
return false;
}
}else{
return false;
}
}
Uses:
Use
getZipcode()
function like the following.$address = 'Rashtrapati Bhawan, Raisina Hills, New Delhi';$zipcode = getZipcode($address);$zipcode = $zipcode?$zipcode:'Not found';
To specify a Google API key
in your request, include it as the value of a key parameter.
$geocodeFromAddr = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddr.'&sensor=true_or_false&key=GoogleAPIKey');
No comments:
Post a Comment