Integrating Google Maps, Places, and Geocode APIs with ASP.NET MVC 5

In this article you will learn how to Integrate Google Maps, Places, and Geocode APIs with ASP.NET MVC 5.

This article describes the practical approach to integrate Google Maps API, Autocomplete Places API, and Geocode API with the ASP.NET MVC 5 application.

Recently, I was working on a project in which I had to select the venue by applying the autocomplete place API, and on the basis of the venue, I had to get the country, state, city, zip code, latitude, and longitude. If user entered the unknown venue then on the basis of Country and Zip code, state and city would be saved.

To complete the requirement, I have used the following Google APIs,

  • Autocomplete Place API
  • Map API
  • Geocode API

In this article, we will create an ASP.NET MVC application and integrate the above APIs with our web application. So, let’s start the procedure with the following sections,

  • Creating ASP.NET MVC Web Application
  • Working with Application

Creating ASP.NET MVC Application

In this section, we’ll create the ASP.NET Web application with the help of MVC project template in Visual Studio 2013. Follow the steps below:

Step 1

Open the Visual Studio and click on a new project and create a new ASP.Net Web Application named “GooglePlaceMVCSample”

Creating Web Application
                           Figure 1: Creating Web Application

Step 2

Select the MVC project template from the next “One ASP.Net wizard”

MVC Project Template
                                 Figure 2: MVC Project Template

That’s it. Your MVC application is created.

Working with Application

In this section, we will work with the existing “HomeController” and “About.cshtml” page or you can create new controller and view to work with the application. At first we will create a new model so that we can bind the view with the mode and pass some data from the controller to view with the help of model.

Let’s start with the following procedure:

Step 1

Right click on the “Models” folder and add a new class named “Venue”,

Adding class to Model
                           Figure 3: Adding class to Model

  1. public class Venue  
  2. {  
  3.     #region Properties  
  4.     public int Id { getset; }  
  5.     [Required(ErrorMessage = "Name is required")]  
  6.     public string Name { getset; }  
  7.     [Required(ErrorMessage = "ZipCode is required")]  
  8.     public string ZipCode { getset; }  
  9.     [Required(ErrorMessage = "Country is required")]  
  10.     public string Country { getset; }  
  11.     public string CountryName { getset; }  
  12.     [Required(ErrorMessage = "State is required")]  
  13.     public string State { getset; }  
  14.     [Required(ErrorMessage = "City is required")]  
  15.     public string City { getset; }  
  16.     public float Latitude { getset; }  
  17.     public float Longitude { getset; }  
  18.     public List<Country> Countries { getset; }  
  19.     public string CountryCode { getset; }  
  20.     #endregion  
  21. }  
  22.   
  23. public class Country  
  24. {  
  25.     #region Properties  
  26.     public int CountryId { getset; }      
  27.     public string CountryName { getset; }      
  28.     public string MapReference { getset; }      
  29.     public string CountryCode { getset; }      
  30.     public string CountryCodeLong { getset; }  
  31.     #endregion  
  32. }  
Step 2

Add a new class as named “CountryModel” and add the following code,
  1. public class CountryModel  
  2. {  
  3.     #region DatabaseMethod  
  4.     public List<T> ConvertTo<T>(DataTable datatable) where T : new()  
  5.     {  
  6.         List<T> Temp = new List<T>();  
  7.         try  
  8.         {  
  9.             List<string> columnsNames = new List<string>();  
  10.             foreach (DataColumn DataColumn in datatable.Columns)  
  11.                 columnsNames.Add(DataColumn.ColumnName);  
  12.             Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));  
  13.             return Temp;  
  14.         }  
  15.         catch  
  16.         {  
  17.             return Temp;  
  18.         }  
  19.   
  20.     }  
  21.     public T getObject<T>(DataRow row, List<string> columnsName) where T : new()  
  22.     {  
  23.         T obj = new T();  
  24.         try  
  25.         {  
  26.             string columnname = "";  
  27.             string value = "";  
  28.             PropertyInfo[] Properties;  
  29.             Properties = typeof(T).GetProperties();  
  30.             foreach (PropertyInfo objProperty in Properties)  
  31.             {  
  32.                 columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());  
  33.                 if (!string.IsNullOrEmpty(columnname))  
  34.                 {  
  35.                     value = row[columnname].ToString();  
  36.                     if (!string.IsNullOrEmpty(value))  
  37.                     {  
  38.                         if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)  
  39.                         {  
  40.                             value = row[columnname].ToString().Replace("$""").Replace(",""");  
  41.                             objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);  
  42.                         }  
  43.                         else  
  44.                         {  
  45.                             value = row[columnname].ToString();  
  46.                             objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);  
  47.                         }  
  48.                     }  
  49.                 }  
  50.             }  
  51.             return obj;  
  52.         }  
  53.         catch  
  54.         {  
  55.             return obj;  
  56.         }  
  57.     }  
  58.     #endregion  
  59.   
  60.     SqlConnection con;  
  61.     SqlDataAdapter adap;  
  62.     DataTable dt;  
  63.     SqlCommand cmd;  
  64.     public CountryModel()  
  65.     {  
  66.         string conn = ConfigurationManager.ConnectionStrings["CountryConnectionString"].ConnectionString;  
  67.         con = new SqlConnection(conn);  
  68.     }  
  69.   
  70.     public List<Country> GetCountries()  
  71.     {  
  72.         List<Country> countries = new List<Country>();  
  73.         try  
  74.         {  
  75.             con.Open();  
  76.             adap = new SqlDataAdapter();  
  77.             dt = new DataTable();  
  78.             cmd = new SqlCommand("GetCountries", con);  
  79.             cmd.CommandType = CommandType.StoredProcedure;  
  80.   
  81.             adap.SelectCommand = cmd;  
  82.             adap.Fill(dt);  
  83.             countries = ConvertTo<Country>(dt);  
  84.         }  
  85.         catch (Exception x)  
  86.         {  
  87.   
  88.         }  
  89.         finally  
  90.         {  
  91.             cmd.Dispose();  
  92.             con.Close();  
  93.         }  
  94.         return countries;  
  95.     }  
  96. }  
Step 3

Open “Web.Config” and add the following connection string code for database,
  1. <add name="CountryConnectionString" connectionString="data source=server name,1436;database=Sample;user id=sa;password=123456;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>  
Note

Change the connection string as per your credentials.

Step 4

Open “HomeController” and edit the code with the following highlighted code,
  1. public ActionResult About()  
  2. {  
  3.     ViewBag.Message = "Your application description page.";  
  4.     List<Country> objCountry = new List<Country>();  
  5.     CountryModel model = new CountryModel();  
  6.     objCountry = model.GetCountries();  
  7.     return View(new Venue { Countries = objCountry });  
  8. }  
Step 5

Now edit the “About.cshtml” page with the following code,
  1. @model GooglePlaceMvcSample.Models.Venue  
  2. @{  
  3.     ViewBag.Title = "About";  
  4.  
  5. <h2>@ViewBag.Title.</h2>  
  6. <h3>@ViewBag.Message</h3>  
  7.   
  8. <p>Use this area to provide additional information.</p>  
  9. <script src="~/Scripts/jquery-2.2.3.js"></script>  
  10. <script src="~/Scripts/jquery-2.2.3.min.js"></script>  
  11. <script src="~/Scripts/jquery-ui-1.11.4.js"></script>  
  12. <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>  
  13. <script src="~/Scripts/jquery.validate.js"></script>  
  14. <div class="row">  
  15.     <div class="col-md-8">  
  16.         <div class="form-group">  
  17.             @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })  
  18.             <div class="col-md-10">  
  19.                 @Html.TextBoxFor(m => m.Name, new { @class = "form-control"id = "TextBoxVenueLocation" })  
  20.                 @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })  
  21.                 @Html.HiddenFor(m => m.Id, new { @id = "EventVenueId" })  
  22.             </div>  
  23.         </div>  
  24.         <div class="form-group">  
  25.             @Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" })  
  26.             <div class="col-md-10">  
  27.                 @Html.DropDownListFor(m => m.CountryCode, new SelectList(Model.Countries, "CountryCode", "CountryName"), "Choose Country", new { @class = "selectBox form-control ", @id = "DropDownListCounties" })  
  28.                 @Html.HiddenFor(m => m.CountryName, new { @id = "HdnCountryName" })  
  29.                 @Html.ValidationMessageFor(m => m.Country, "", new { @class = "text-danger" })  
  30.             </div>  
  31.         </div>  
  32.         <div class="form-group">  
  33.             @Html.LabelFor(m => m.ZipCode, new { @class = "col-md-2 control-label" })  
  34.             <div class="col-md-10">  
  35.                 @Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control"id = "TextBoxZipCode"maxlength = 6 })  
  36.                 @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })  
  37.             </div>  
  38.         </div>  
  39.         <div class="form-group">  
  40.             @Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })  
  41.             <div class="col-md-10">  
  42.                 @Html.TextBoxFor(m => m.State, new { @class = "form-control"id = "TextBoxState" })  
  43.                 @Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })  
  44.             </div>  
  45.         </div>  
  46.         <div class="form-group">  
  47.             @Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })  
  48.             <div class="col-md-10">  
  49.                 @Html.TextBoxFor(m => m.City, new { @class = "form-control"id = "TextBoxCity" })  
  50.                 @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })  
  51.             </div>  
  52.         </div>  
  53.         @Html.HiddenFor(m => m.Latitude, new { @id = "EventVenueLatitude" })  
  54.         @Html.HiddenFor(m => m.Longitude, new { @id = "EventVenueLongitude" })          
  55.             </div>  
  56.         </div>  
  57.     </div>  
  58. </div>  
Step 6

Open the Content-> Site.css and add the following code in the bottom,
  1. .selectBox{width:295px;height:38px;padding: 0 0 0 9px;}  
  2. select option{width:255px;}  
Step 7

Save the application and debug it.

Model Binded Vew in MVC 5
                           Figure 4: Model Binded Vew in MVC 5

Creating Google Autocomplete Place API Key

At first for accessing the autocomplete place API, you have to create an API Key to access that places API url. To create an API key, follow the steps below:

Step 1

Go to Google Developer Console,

Step 2

Login with your Gmail account and click on Continue to “Create New Project”,

Creating New Project in Google APIs
               Figure 5: Creating New Project in Google APIs

Step 3

Enter the name for API Key as shown below,

Create Server API Key
                              Figure 6: Create Server API Key

Step 4

Now, you can copy your API Key from the next wizard.

API key Info
                                 Figure 7: API key Info

Step 5

Open WebConfig in your project and add a key in the AppSettings tab as shown in the code below,
  1. <add key="GooglePlaceAPIKey" value="Your API Key"></add>  
Note

Please change the value with your API Key.

Adding Google Autocomplete Place API

In this section we will apply the Google autocomplete place API. We will return the response in the json format so that it is easy to convert the json result to list. We can also use XML format to get the API result.

Now start with the following steps,

Step 1

At first we will add a class in our model. Add the following code in your Venue class,
  1. public class Prediction  
  2. {  
  3.     public string description { getset; }  
  4.     public string id { getset; }  
  5.     public string place_id { getset; }  
  6.     public string reference { getset; }  
  7.     public List<string> types { getset; }  
  8. }  
  9. public class RootObject  
  10. {  
  11.     public List<Prediction> predictions { getset; }  
  12.     public string status { getset; }  
  13. }  
Step 2

Now just add the following key in your WebConfig file for accessing the place api url.
  1. <add key="GooglePlaceAPIUrl" value="https://maps.googleapis.com/maps/api/place/autocomplete/json?input={0}&types=geocode&language=en&key={1}"/>  
Step 3

Now create an action method in the HomeController with the help of the following code,
  1. /// <summary>  
  2. /// This method is used to get the place list  
  3. /// </summary>  
  4. /// <param name="SearchText"></param>  
  5. /// <returns></returns>  
  6. [HttpGet, ActionName("GetEventVenuesList")]  
  7. public JsonResult GetEventVenuesList(string SearchText)  
  8. {  
  9.     string placeApiUrl = ConfigurationManager.AppSettings["GooglePlaceAPIUrl"];  
  10.              
  11.     try  
  12.     {  
  13.         placeApiUrl = placeApiUrl.Replace("{0}", SearchText);  
  14.         placeApiUrl = placeApiUrl.Replace("{1}", ConfigurationManager.AppSettings["GooglePlaceAPIKey"]);  
  15.   
  16.         var result = new System.Net.WebClient().DownloadString(placeApiUrl);  
  17.         var Jsonobject = JsonConvert.DeserializeObject<RootObject>(result);  
  18.   
  19.         List<Prediction> list = Jsonobject.predictions;  
  20.   
  21.         return Json(list, JsonRequestBehavior.AllowGet);  
  22.     }  
  23.     catch (Exception ex)  
  24.     {  
  25.         return Json(ex.Message, JsonRequestBehavior.AllowGet);  
  26.     }  
  27. }  
Step 4

Now open the “About.cshtml” page and add the following script,
  1. <script type="text/javascript">  
  2.     $(function () {          
  3.         $("#TextBoxVenueLocation").autocomplete({  
  4.             source: function (request, response) {  
  5.                 $.ajax({  
  6.                     url: "@Url.Action("GetEventVenuesList", "Home")",  
  7.                     data: { SearchText: request.term },  
  8.                     dataType: "json",  
  9.                     type: "GET",  
  10.                     success: function (data) {  
  11.                         if (data.length == 0) {  
  12.                             $('#EventVenueId').val("");  
  13.                             $('#VenueLocationMesssage').show();                              
  14.                             return false;  
  15.                         }  
  16.                         else {  
  17.                             response($.map(data, function (item) {  
  18.                                 return {                                      
  19.                                     label: item.description,  
  20.                                     value: item.place_id  
  21.                                 }  
  22.                             }));  
  23.                         }  
  24.                     },  
  25.                     error: function (x, y, z) {  
  26.                         alert('error');  
  27.                     }  
  28.                 });  
  29.             },  
  30.             messages: {  
  31.                 noResults: "", results: ""  
  32.             },  
  33.             select: function (event, ui) {  
  34.                 $('#TextBoxVenueLocation').val(ui.item.label);  
  35.                 $('#EventVenueId').val(ui.item.value);   
  36.                 return false;  
  37.             }  
  38.         }).autocomplete("widget").addClass("CitiesAutocomplete");  
  39.     });  
  40. </script>  
  41. @section Scripts {  
  42.     @Scripts.Render("~/bundles/jqueryval")  
  43. }   
Step 5

Now add the following css code in the Site.css file,
  1. .CitiesAutocomplete{list-style:none;background:#fbfbfb;border:1px solid #5f5f5f!important;width:350px !important;position:absolute;z-index:10000;border-top:none;min-height:25px;max-height:250px;overflow: auto;cursor:pointer; padding: 4px 0;}  
  2. .CitiesAutocomplete li{padding: 2px 6px;}  
  3. .CitiesAutocomplete li:hover{background-color:#9eeffe; }  
Step 6

Now run the application and you will get the location as you type in the Name textbox. As you type in the textbox, the places will be displayed,

Autocomplete Place API Result
               Figure 8: Autocomplete Place API Result

We have successfully completed the add Place API. Now, we’ll move to the next section.

Adding Google Map API for Place Details

In this section, we will get all the place details like Country, State, City, Address, Zipcode, Latitude or Longitude etc by using the Google MAP API. We have to pass the PlaceId which will get from the Autocomplete API places. We will get the API result in the XML format and fetch the necessary details from the API result.

Start with the following steps

Step 1

Add the following API url in the webconfig file,
  1. <add key="GooglePlaceDetailsAPIUrl" value="https://maps.googleapis.com/maps/api/place/details/xml?placeid={0}&key={1}"/>  
Step 2

Add the following methods in the “HomeController”:
  1. /// <summary>  
  2. /// This method is used to get place details on the basis of PlaceID  
  3. /// </summary>  
  4. /// <param name="placeId"></param>  
  5. /// <returns></returns>  
  6. [HttpGet, ActionName("GetVenueDetailsByPlace")]  
  7. public JsonResult GetVenueDetailsByPlace(string placeId)  
  8. {  
  9.     string placeDetailsApi = ConfigurationManager.AppSettings["GooglePlaceDetailsAPIUrl"];  
  10.     try  
  11.     {  
  12.         Venue ven = new Venue();  
  13.         placeDetailsApi = placeDetailsApi.Replace("{0}", placeId);  
  14.         placeDetailsApi = placeDetailsApi.Replace("{1}", ConfigurationManager.AppSettings["GooglePlaceAPIKey"]);  
  15.   
  16.         var result = new System.Net.WebClient().DownloadString(placeDetailsApi);  
  17.   
  18.         var xmlElm = XElement.Parse(result);  
  19.         ven = GetAllVenueDetails(xmlElm);  
  20.   
  21.         return Json(ven, JsonRequestBehavior.AllowGet);  
  22.     }  
  23.     catch (Exception ex)  
  24.     {  
  25.         return Json(ex.Message, JsonRequestBehavior.AllowGet);  
  26.     }  
  27. }  
  28. /// <summary>  
  29. /// This method is creted to get the place details from xml  
  30. /// </summary>  
  31. /// <param name="xmlElm"></param>  
  32. /// <returns></returns>  
  33. private Venue GetAllVenueDetails(XElement xmlElm)  
  34. {  
  35.     Venue ven = new Venue();  
  36.     List<string> c = new List<string>();  
  37.     List<string> d = new List<string>();  
  38.     //get the status of download xml file  
  39.     var status = (from elm in xmlElm.Descendants()  
  40.                     where  
  41.                         elm.Name == "status"  
  42.                     select elm).FirstOrDefault();  
  43.   
  44.     //if download xml file status is ok  
  45.     if (status.Value.ToLower() == "ok")  
  46.     {  
  47.   
  48.         //get the address_component element  
  49.         var addressResult = (from elm in xmlElm.Descendants()  
  50.                                 where  
  51.                                     elm.Name == "address_component"  
  52.                                 select elm);  
  53.         //get the location element  
  54.         var locationResult = (from elm in xmlElm.Descendants()  
  55.                                 where  
  56.                                     elm.Name == "location"  
  57.                                 select elm);  
  58.   
  59.         foreach (XElement item in locationResult)  
  60.         {  
  61.             ven.Latitude = float.Parse(item.Elements().Where(e => e.Name.LocalName == "lat").FirstOrDefault().Value);  
  62.             ven.Longitude = float.Parse(item.Elements().Where(e => e.Name.LocalName == "lng").FirstOrDefault().Value);  
  63.         }  
  64.         //loop through for each address_component  
  65.         foreach (XElement element in addressResult)  
  66.         {  
  67.             string type = element.Elements().Where(e => e.Name.LocalName == "type").FirstOrDefault().Value;  
  68.   
  69.             if (type.ToLower().Trim() == "locality"//if type is locality the get the locality  
  70.             {  
  71.                 ven.City = element.Elements().Where(e => e.Name.LocalName == "long_name").Single().Value;  
  72.             }  
  73.             else  
  74.             {  
  75.                 if (type.ToLower().Trim() == "administrative_area_level_2" && string.IsNullOrEmpty(ven.City))  
  76.                 {  
  77.                     ven.City = element.Elements().Where(e => e.Name.LocalName == "long_name").Single().Value;  
  78.                 }  
  79.             }  
  80.             if (type.ToLower().Trim() == "administrative_area_level_1"//if type is locality the get the locality  
  81.             {  
  82.                 ven.State = element.Elements().Where(e => e.Name.LocalName == "long_name").Single().Value;  
  83.             }  
  84.             if (type.ToLower().Trim() == "country"//if type is locality the get the locality  
  85.             {  
  86.                 ven.Country = element.Elements().Where(e => e.Name.LocalName == "long_name").Single().Value;  
  87.                 ven.CountryCode = element.Elements().Where(e => e.Name.LocalName == "short_name").Single().Value;  
  88.                 if (ven.Country == "United States") { ven.Country = "USA"; }  
  89.             }  
  90.             if (type.ToLower().Trim() == "postal_code"//if type is locality the get the locality  
  91.             {  
  92.                 ven.ZipCode = element.Elements().Where(e => e.Name.LocalName == "long_name").Single().Value;  
  93.             }  
  94.         }  
  95.     }  
  96.     xmlElm.RemoveAll();  
  97.     return ven;  
  98. }  
Note

In the above code, there are two methods, the first one is used to call the api and get the api result in the xml format. Second method is used to get all the required place details like Country, State, City, Latitude and Longitude. You can fetch the details from the json result also.

Step 3

In the “About.cshtml” page, update the autocomplete method with the help of the  highlighted code below:

Change the select method in autocomplete
  1. select: function (event, ui) {  
  2.     $('#TextBoxVenueLocation').val(ui.item.label);  
  3.     $('#EventVenueId').val(ui.item.value);  
  4.     GetVenueDetailsByPlaceId(ui.item.value);  
  5.     return false;  
  6. }  
Add the following function in the script
  1. function GetVenueDetailsByPlaceId(PlaceId) {  
  2.     $.ajax({  
  3.         url: '@Url.Action("GetVenueDetailsByPlace", "home")',   
  4.         dataType: "json",  
  5.         data: {  
  6.             placeId: PlaceId  
  7.         },  
  8.         type: "GET",  
  9.         async: false,  
  10.         error: function (xhr, status, error) {  
  11.             var err = eval("(" + xhr.responseText + ")");  
  12.             toastr.error(err.message);  
  13.         },  
  14.         success: function (data) {  
  15.             $('#TextBoxZipCode').val(data.ZipCode);  
  16.             $('#DropDownListCounties option:selected').text(data.Country);  
  17.             $('#TextBoxState').val(data.State);  
  18.             $('#TextBoxCity').val(data.City);  
  19.             $('#EventVenueLatitude').val(data.Latitude);  
  20.             $('#EventVenueLongitude').val(data.Longitude);  
  21.         },  
  22.         beforeSend: function () {  
  23.             $("#divProcessing").show();  
  24.         }  
  25.     });  
  26. }  
Step 4

Now with the help of this code, we will fetch the place details and display the details in the textbox. Run the application and search for any genuine place.

Searching Place using Autocomplete API
            Figure 9: Searching Place using Autocomplete API

Now select the place,

Place Details using MAP Place API
               Figure 10: Place Details using MAP Place API

That’s it with this section. Now we’ll move to further sections.

Adding Google Geocode API

In this section, we’ll use the Google Geocode API to get the place details in case there are no matching records displayed in the autocomplete API result. So in that case, we can get the place details by providing the Zip code and country as a region in the api.

Let’s start with the following steps:

Step 1

Add the following API url in the Web.Config file,
  1. <add key="GoogleGeocodeAPIUrl" value="https://maps.googleapis.com/maps/api/geocode/xml?address={0}&region={1}&key={2}"/>  
Step 2

Add the following method in the “HomeController”,
  1. /// <summary>  
  2. /// This mehthod is created to get the place details on the basis of zip code and country  
  3. /// </summary>  
  4. /// <param name="zipCode"></param>  
  5. /// <param name="region"></param>  
  6. /// <returns></returns>  
  7. [HttpGet, ActionName("GetVenueDetailsByZipCode")]  
  8. public JsonResult GetVenueDetailsByZipCode(string zipCode, string region)  
  9. {  
  10.     string geocodeApi = ConfigurationManager.AppSettings["GoogleGeocodeAPIUrl"];  
  11.     try  
  12.     {  
  13.         Venue ven = new Venue();  
  14.         geocodeApi = geocodeApi.Replace("{0}", zipCode);  
  15.         geocodeApi = geocodeApi.Replace("{1}", region);  
  16.         geocodeApi = geocodeApi.Replace("{2}", ConfigurationManager.AppSettings["GooglePlaceAPIKey"]);  
  17.   
  18.         var result = new System.Net.WebClient().DownloadString(geocodeApi);  
  19.   
  20.         var xmlElm = XElement.Parse(result);  
  21.         ven = GetAllVenueDetails(xmlElm);  
  22.         return Json(ven, JsonRequestBehavior.AllowGet);  
  23.     }  
  24.     catch (Exception ex)  
  25.     {  
  26.         return Json(ex.Message, JsonRequestBehavior.AllowGet);  
  27.     }  
  28. }  
Step 3

Now add the following function in the “About.cshtml” page,
  1. /*This method is used to accept only numeric.*/  
  2. $("#TextBoxZipCode").keydown(function (e) {  
  3.     // Allow: backspace, delete, tab, escape, enter and .  
  4.     if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||  
  5.         // Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A  
  6.         ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||  
  7.         // Allow: home, end, left, right, down, up  
  8.         (e.keyCode >= 35 && e.keyCode <= 40)) {  
  9.         // let it happen, don't do anything  
  10.         return;  
  11.     }  
  12.     // Ensure that it is a number and stop the keypress  
  13.     if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {  
  14.         $("#TextBoxZipCode").val('');  
  15.         e.preventDefault();  
  16.         return false;  
  17.     }  
  18. });  
  19.   
  20. var timer;  
  21. $("#TextBoxZipCode").on('keyup', function (event) {  
  22.     clearTimeout(timer);  //clear any running timeout on key up  
  23.     timer = setTimeout(function () { //then give it a second to see if the user is finished  
  24.         if ($('#DropDownListCounties option:selected').val() == '' && $("#TextBoxZipCode").val() != '') {  
  25.             alert('Country is required');  
  26.             $("#TextBoxZipCode").val('');  
  27.             return false;  
  28.         }  
  29.         else {  
  30.             $.ajax({  
  31.                 url: '@Url.Action("GetVenueDetailsByZipCode", "home")',   
  32.                 dataType: "json",  
  33.                 data: {  
  34.                     zipCode: $("#TextBoxZipCode").val(), region: $("#DropDownListCounties").val()  
  35.                 },  
  36.                 type: "GET",  
  37.                 async: false,  
  38.                 error: function (xhr, status, error) {  
  39.                     var err = eval("(" + xhr.responseText + ")");  
  40.                     toastr.error(err.message);  
  41.                 },  
  42.                 success: function (data) {  
  43.                     $('#TextBoxZipCode').val(data.ZipCode);  
  44.                     $('#TextBoxState').val(data.State);  
  45.                     $('#TextBoxCity').val(data.City);  
  46.                     $('#EventVenueLatitude').val(data.Latitude);  
  47.                     $('#EventVenueLongitude').val(data.Longitude);  
  48.                 },  
  49.                 beforeSend: function () {  
  50.                     $("#divProcessing").show();  
  51.                 }  
  52.             });  
  53.         }  
  54.     }, 500);  
  55. });  
Note

With the help of the above code, the user can only enter numbers in the zip code textbox and after entering the number, the API result will be displayed. I have made the country required because in many cities zip codes arethe same so in that case, region (country) will be helpful to get the particular result.

Note about API KEY

If your API key will not get the result or there is some error generated to get the result then you go here and create the new API key for Geocode API.

Step 4

Now run the application and search the place, if the place is not  listed in the api result, just select the country at first and then enter the zip code and you will get the result from the Geocode API.

Place Details using Geocode API
               Figure 11: Place Details using Geocode API

That’s it for this article.

Summary

This article described how we can use different Google provided APIs and how to integrate Google APIs in the ASP.Net MVC Application.