Introduction: In 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.
Implementation: Let's create an asp.net web application to understand.
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.
Click on image to enlarge |
Source Code:
C#.NET Code to Get city, state and country based on zip code using Google map API in asp.net
- 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">
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:
<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> </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>
- Now in the code behind file(.aspx.cs) write the code on Button click events as:
protected void btnSubmit_Click(object
sender, EventArgs e)
VB.Net Code to Get city, state and country based on zip code using Google map API in asp.net
{
FillCityStateCountry();
}
private void FillCityStateCountry()
{
txtCity.Text = hdCity.Value;
txtState.Text = hdState.Value;
txtCountry.Text = hdCountry.Value;
}
- Now in the code behind file(.aspx.vb) write the code on Button click events as:
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."
44 comments
Click here for commentsI could retrieve only city and country.
ReplyHello ivan..recheck your code because this is completely working and live code..if u still face problem..then let me know.
Replysir from where i can get database all country , state and cities . so that i can make it for all country
ReplyHello 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
Replysir How i know the zip code for all states and countries
Replyhi suresh..u can search on google for the same..
ReplyNICE WORK SIR THANK YOU
Replyyour welcome prasad thonta..stay tuned and subscribe for more updates like this.
Replywant 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
Replyhello Amzad Raza khan..read the below mentioned article as per your requirement.
ReplyHow 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
Sir I am using above code but data is not fetch from google API tell me sir ..
ReplyI Follow the same instruction but after filling zipcode i cant retrive city,State,Country
ReplyIs your javascript enabled or not? this is important because it uses javascript. let me know after checking..
ReplyIs your javascript enabled or not? this is important because it uses javascript. let me know after checking..
Replydear sir,
Replyhow to check javascript enabled or not?
You will get the idea after reading the following article:
ReplyHow to enable JavaScript in asp.net using C#,VB.Net
http://www.webcodeexpert.com/2013/06/how-to-enable-javascript-in-aspnet.html
Like this article can we find address using post code of uk("ncrw 118") like this format
ReplyHi sir, i use this code but it is unable to fetch the data .
Replywhile going in through the breakpoint it shows console is not defined
Hello siva krishna kodali..i suggest you to recheck all your code and also test it on different browsers..It will definitely work..
Replysir, any other ways to Get zip code based on using city, state and country based Google map API in asp.net
ReplyHi Kamal.there are multiple other ways to get this...but up to now i have used this way only..
Replysir i need zip code for a city based on giving input city,state,country,,,,
Replyif u know othrr ways to get it.......plz update code...
Sir m gettiing an error that onblur is not an attribute of textbox..
ReplyHello Aniket remove the onblur attribute from textbox and try adding it on page load event as:
Replyprotected void Page_Load(object sender, EventArgs e)
{
txtZipCode.Attributes.Add("onblur", "getLocation()");
}
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)
Replyhii,
Replyits work fine for me
Thank you
in the above code
Replywhat is replace code for
'### google maps api ###'
Hello Ramesh..there is no need to replace anything..it works as it is..please try and notify me..
ReplyHello,
ReplyCan you provide code for fetching latitude & longitude from zipcode.
Hello Prasanna Kumar Muduli..i will create an article as per your requirement and upload it very soon..so stay connected and keep reading..;)
ReplyThank you sir. Code is working for me. But some times did not show city .
ReplyThank You
thanks for appreciating my work..stay connected and keep reading for more useful updates like this
ReplyThanks,
ReplySir, Its working very fine and smooth.
I really appreciate you for such a great Work.
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..
ReplyHi Lalit Raghuvanshi , how to display county using zip code
Replyhi raghuvanshi , how to search county using zip code
Replyhow can i get live list of active airports across the world in my drop down list ?
ReplyHelp me if you can
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
ReplyHello Kunigiti Indraja..i think you are missing Form tag inside the Body tag
ReplyHello Lalit, the code works great, thx a lot for the same, i have 2 questions.
Reply1. 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
The code works great, Thanks a lot..
ReplyI am glad you found this article helpful..stay connected and keep reading for more useful updates
ReplyThanx this example is working fine but can u please explain me the code by commenting on it
ReplyThanks a ton
ReplyIf 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..