Get city, state and country based on zip code using Google map API in asp.net

IntroductionIn previous articles i explained How to Fill Country,State,Cities in the DropDownList in asp.net C#,VB.Net and Convert Rupees,Currency or Numbers to Words and Get age in years,months,days,hours and seconds from DOB and Jquery form validations in asp.net and  How to add meta description,meta keywords tags from code behind in asp.net(C#, VB) and How to create XML file and Bind XML data to CheckBoxList using DataSet in asp.net.
Now in this article I will explain with example How to get/fetch City, State and Country automatically based on Zip Code/Postal code i.e. when you enter Zip code and press Fill city, state and country button it will automatically fetch corresponding City, State and Country using Google map API. It can also be done by having tables in the database for zip code and their corresponding city, state and country. But it is very difficult to enter all the zip codes and their city, state and country information in the table and fetching that on the basis of zip code. Google map API provides us the easiest way to do this. Let’s understand by an example.

fill city, state and country based on zipcode example in asp.net
Click on image to enlarge
Implementation:  Let's create an asp.net web application to understand.

Source Code:
  • In the <HEAD> tag of the design page(.aspx) add reference to Google map API and also create JavaScript function as shown below:
<script language="javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>

    <script language="javascript">
        function getLocation() {
            getAddressInfoByZip(document.forms[0].txtZipCode.value);
        }

        function response(obj) {
            console.log(obj);
        }
        function getAddressInfoByZip(zip)
        {
            if (zip.length >= 5 && typeof google != 'undefined') {
                var addr = {};
                var geocoder = new google.maps.Geocoder();
                geocoder.geocode({ 'address': zip }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        if (results.length >= 1) {
                            for (var ii = 0; ii < results[0].address_components.length; ii++) {
                                var street_number = route = street = city = state = zipcode = country = formatted_address = '';
                                var types = results[0].address_components[ii].types.join(",");
                                if (types == "street_number") {
                                    addr.street_number = results[0].address_components[ii].long_name;
                                }
                                if (types == "route" || types == "point_of_interest,establishment") {
                                    addr.route = results[0].address_components[ii].long_name;
                                }
                                if (types == "sublocality,political" || types == "locality,political" || types == "neighborhood,political" || types == "administrative_area_level_3,political") {
                                    addr.city = (city == '' || types == "locality,political") ? results[0].address_components[ii].long_name : city;
                                   
                                    document.getElementById("<%= hdCity.ClientID %>").value = addr.city;
                                }
                                if (types == "administrative_area_level_1,political") {
                                    addr.state = results[0].address_components[ii].short_name;                                           
                                 
                                    document.getElementById("<%= hdState.ClientID %>").value = addr.state;                                    
                                }
                                if (types == "postal_code" || types == "postal_code_prefix,postal_code") {
                                    addr.zipcode = results[0].address_components[ii].long_name;                                  
                                }
                                if (types == "country,political") {
                                    addr.country = results[0].address_components[ii].long_name;

                                    document.getElementById("<%= hdCountry.ClientID %>").value = addr.country;
                                }
                            }
                            addr.success = true;
                            for (name in addr) {
                                console.log('### google maps api ### ' + name + ': ' + addr[name]);
                            }
                            response(addr);
                    
                        } else {
                            response({ success: false });
                        }
                    } else {
                        response({ success: false });
                    }
                });
            } else {
                response({ success: false });
            }       
          }
</script>
  • Now in the <BODY> tag of the design page(.aspx) place three TextBox controls and a Button control as:
<fieldset style="width:435px">
            <legend>Fill city,state and country Example</legend>
            <table>  
                <tr>
                    <td>ZipCode</td>
                    <td>
                        <asp:TextBox ID="txtZipCode" runat="server" onblur="getLocation();"></asp:TextBox>
                        <asp:Button ID="btnSubmit" runat="server" Text="Fill city,state,country" OnClick="btnSubmit_Click" />
                    </td>
                </tr>
                <tr>
                    <td>City</td>
                    <td>
                        <asp:TextBox ID="txtCity" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>State</td>
                    <td>
                        <asp:TextBox ID="txtState" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Country</td>
                    <td>
                        <asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>                       
                        <asp:HiddenField ID="hdCity" runat="server" Value="" />
                        <asp:HiddenField ID="hdState" runat="server" Value="" />
                        <asp:HiddenField ID="hdCountry" runat="server" Value="" />
                    </td>
                </tr>
            </table>
        </fieldset>


C#.NET Code to Get city, state and country based on zip code using Google map API in asp.net
  • Now in the code behind file(.aspx.cs) write the code on Button click events as:
 protected void btnSubmit_Click(object sender, EventArgs e)
        {
           FillCityStateCountry();
        }

        private void FillCityStateCountry()
        {
            txtCity.Text = hdCity.Value;
            txtState.Text = hdState.Value;
            txtCountry.Text = hdCountry.Value;
        }    


VB.Net Code to Get city, state and country based on zip code using Google map API in asp.net
  • Now in the code behind file(.aspx.vb) write the code on Button click events as:
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) handles  btnSubmit_Click
                    FillCityStateCountry()
End Sub

Private Sub FillCityStateCountry()
                    txtCity.Text = hdCity.Value
                    txtState.Text = hdState.Value
                    txtCountry.Text = hdCountry.Value
End Sub 

Now over to you:
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

44 comments

Click here for comments
Ivan
admin
July 29, 2013 ×

I could retrieve only city and country.

Reply
avatar
July 29, 2013 ×

Hello ivan..recheck your code because this is completely working and live code..if u still face problem..then let me know.

Reply
avatar
Unknown
admin
July 30, 2013 ×

sir from where i can get database all country , state and cities . so that i can make it for all country

Reply
avatar
July 30, 2013 ×

Hello amit..for this article you don't need the database..Using Google API it automatically fetches the county, state and city based on zip code you enter

Reply
avatar
suresh
admin
August 07, 2013 ×

sir How i know the zip code for all states and countries

Reply
avatar
August 07, 2013 ×

hi suresh..u can search on google for the same..

Reply
avatar
Unknown
admin
August 13, 2013 ×

NICE WORK SIR THANK YOU

Reply
avatar
August 13, 2013 ×

your welcome prasad thonta..stay tuned and subscribe for more updates like this.

Reply
avatar
Unknown
admin
September 03, 2013 ×

want to fiil dropdownlist with country and state on selection of country in seconddropdwon and city on selection of state in third dropdwon in asp.net

Reply
avatar
September 03, 2013 ×

hello Amzad Raza khan..read the below mentioned article as per your requirement.

How to Fill Country,State,Cities in the DropDownList in asp.net C#,VB.Net
http://www.webcodeexpert.com/2013/07/how-to-fill-countrystatecities-in.html

Reply
avatar
Sonu
admin
September 11, 2013 ×

Sir I am using above code but data is not fetch from google API tell me sir ..

Reply
avatar
Anonymous
admin
September 11, 2013 ×

I Follow the same instruction but after filling zipcode i cant retrive city,State,Country

Reply
avatar
September 11, 2013 ×

Is your javascript enabled or not? this is important because it uses javascript. let me know after checking..

Reply
avatar
September 11, 2013 ×

Is your javascript enabled or not? this is important because it uses javascript. let me know after checking..

Reply
avatar
Anonymous
admin
September 13, 2013 ×

dear sir,
how to check javascript enabled or not?

Reply
avatar
September 13, 2013 ×

You will get the idea after reading the following article:

How to enable JavaScript in asp.net using C#,VB.Net
http://www.webcodeexpert.com/2013/06/how-to-enable-javascript-in-aspnet.html

Reply
avatar
Unknown
admin
September 25, 2013 ×

Like this article can we find address using post code of uk("ncrw 118") like this format

Reply
avatar
October 18, 2013 ×

Hi sir, i use this code but it is unable to fetch the data .
while going in through the breakpoint it shows console is not defined

Reply
avatar
October 22, 2013 ×

Hello siva krishna kodali..i suggest you to recheck all your code and also test it on different browsers..It will definitely work..

Reply
avatar
Unknown
admin
November 14, 2013 ×

sir, any other ways to Get zip code based on using city, state and country based Google map API in asp.net

Reply
avatar
November 14, 2013 ×

Hi Kamal.there are multiple other ways to get this...but up to now i have used this way only..

Reply
avatar
Unknown
admin
November 15, 2013 ×

sir i need zip code for a city based on giving input city,state,country,,,,
if u know othrr ways to get it.......plz update code...

Reply
avatar
Unknown
admin
December 05, 2013 ×

Sir m gettiing an error that onblur is not an attribute of textbox..

Reply
avatar
December 07, 2013 ×

Hello Aniket remove the onblur attribute from textbox and try adding it on page load event as:
protected void Page_Load(object sender, EventArgs e)
{
txtZipCode.Attributes.Add("onblur", "getLocation()");
}

Reply
avatar
Unknown
admin
December 07, 2013 ×

hiii sir...m not getting any errors but when i entered the zipcode its unable to fetch data,i even tried it on internet explorer in that m getting an error " Unable to get property 'value' of undefined or null reference"...also i enable the javascripts in both the browser i.e (mozilla and IE)

Reply
avatar
Unknown
admin
December 19, 2013 ×

hii,

its work fine for me

Thank you

Reply
avatar
Ramesh kumar
admin
December 28, 2013 ×

in the above code

what is replace code for
'### google maps api ###'

Reply
avatar
December 28, 2013 ×

Hello Ramesh..there is no need to replace anything..it works as it is..please try and notify me..

Reply
avatar
December 31, 2013 ×

Hello,
Can you provide code for fetching latitude & longitude from zipcode.

Reply
avatar
January 02, 2014 ×

Hello Prasanna Kumar Muduli..i will create an article as per your requirement and upload it very soon..so stay connected and keep reading..;)

Reply
avatar
ARUN
admin
February 14, 2014 ×

Thank you sir. Code is working for me. But some times did not show city .
Thank You

Reply
avatar
February 14, 2014 ×

thanks for appreciating my work..stay connected and keep reading for more useful updates like this

Reply
avatar
Anonymous
admin
February 19, 2014 ×

Thanks,

Sir, Its working very fine and smooth.
I really appreciate you for such a great Work.

Reply
avatar
February 19, 2014 ×

Hi kavita..thanks for your feedback..it is always nice to hear that my article helped anyone..stay connected and keep reading for more useful updates..

Reply
avatar
Unknown
admin
March 07, 2014 ×

Hi Lalit Raghuvanshi , how to display county using zip code

Reply
avatar
naresh
admin
March 07, 2014 ×

hi raghuvanshi , how to search county using zip code

Reply
avatar
Anonymous
admin
April 17, 2014 ×

how can i get live list of active airports across the world in my drop down list ?
Help me if you can

Reply
avatar
Unknown
admin
April 18, 2014 ×

hi , i am getting error that Control 'txtZipCode' of type 'TextBox' must be placed inside a form tag with runat=server.what can i do

Reply
avatar
April 26, 2014 ×

Hello Kunigiti Indraja..i think you are missing Form tag inside the Body tag

Reply
avatar
Anonymous
admin
May 14, 2014 ×

Hello Lalit, the code works great, thx a lot for the same, i have 2 questions.
1. why cant you write into the textboxes in javascript itself, why do u need a submit button
2. is there any way to restrict the search to india only?
Regards
NR

Reply
avatar
Nirav D
admin
August 25, 2015 ×

The code works great, Thanks a lot..

Reply
avatar
September 02, 2015 ×

I am glad you found this article helpful..stay connected and keep reading for more useful updates

Reply
avatar
Unknown
admin
January 14, 2016 ×

Thanx this example is working fine but can u please explain me the code by commenting on it

Reply
avatar
BT
admin
December 08, 2017 ×

Thanks a ton

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..