Get Zipcode from Address using Google Maps API and PHP

A zip code or postal code makes an address more accurate and helps to know the correct location. There are many online services available to get zipcodes by address. But if you want to get the zipcode from address dynamically, an API service needs to be used.

For some specific cases of the web application, we need to retrieve zipcode from address dynamically. You can extract postal code from address with Google Maps Geocoding API using PHP. In this tutorial, we will show you how to get zipcode from address using Geocoding API and PHP.

Google Maps API Key

The Google Maps API Key is required to post request to Geocoding API and get response. Before getting started to extract zipcode from address, create an API key on the Google Cloud console.

  • Go to the Google Cloud console.
  • Select the project from the Project drop-down menu at the top. If you don’t have an existing project, create a new one.
  • In the left navigation pane, select the APIs & Services » Credentials.
  • In the Credentials page, select CREATE CREDENTIALS » API key.
  • The API key will be created and a dialog will appear with the newly created API key.
  • Navigate to the Library page from the left menu panel and make sure the Geocoding API is enabled.

Copy this API key for later use in the script on the Google Maps Geocoding API request.

Get Zipcode from Address using PHP

The following example code shows steps to find zipcode from a given address using Google Geocoding API and PHP.

  • Set the required parameter in the defined variables.
    • $GOOGLE_API_KEY – Specify the Google API Key.
    • $address – Specify the address from which you want to get postal code.
  • Format the address by replacing the blank space with a plus sign (+).
  • Request Geocoding API (https://maps.googleapis.com/maps/api/geocode/json) using the file_get_contents() method in PHP.
  • Pass address and key parameters in the Geocoding API URL as query string.
  • Decode JSON response returned by the Geocoding API using PHP json_decode() function.
  • Get postal_code from the address_components object of API response.
<?php 

// Google Maps API Key
$GOOGLE_API_KEY 'YOUR_API_KEY_HERE';

// Address from which the zipcode will be retrieved
$address 'White House, Pennsylvania Avenue Northwest, Washington, United States';

// Formatted address
$address_fmt str_replace(array(' ''&'), '+'$address);

// Get geo data from Google Maps API by address
$geodataFromAddr file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?address={$address_fmt}&key={$GOOGLE_API_KEY}");

// Decode JSON data returned by API
$apiResponse json_decode($geodataFromAddr);

if(!empty(
$apiResponse->error_message)){ 
    die(
"API Error: ".$apiResponse->error_message); 
}

if(!empty(
$apiResponse->results[0])){
    
// Retrieve latitude and longitude from API data
    
$latitude  $apiResponse->results[0]->geometry->location->lat
    
$longitude $apiResponse->results[0]->geometry->location->lng;

    if(!empty(
$latitude) && !empty($longitude)){
        
// Get geo data from Google Maps API by latlng
        
$geodataFromLatLon file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng={$latitude},{$longitude}&key={$GOOGLE_API_KEY}");

        
// Decode JSON data returned by API
        
$apiResponse json_decode($geodataFromLatLon);

        if(!empty(
$apiResponse->error_message)){ 
            die(
"API Error: ".$apiResponse->error_message); 
        }

        if(!empty(
$apiResponse->results[0])){
            
$address_components $apiResponse->results[0]->address_components;
            foreach(
$address_components as $acp_row){
                if(
$acp_row->types[0] == 'postal_code'){
                    
$postal_code $acp_row->long_name;
                }
            }
        }
    }
}

?>

Display zipcode of the given address on the web page.

// Render the zipcode of the given address 
echo 'Zipcode: '.$postal_code;

Get Latitude and Longitude from Address using PHP

Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request

4 Comments

  1. Arvind Gondaliya Said...
  2. James Jones Said...
  3. Arun Verma Said...
  4. Sagar Said...

Leave a reply

keyboard_double_arrow_up