cookieChoices = {};

Friday, 20 September 2013

Get city, state and country based on zip code using Google map API 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;
        }    

No comments:

Post a Comment