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”.

Figure 1: Creating Web Application
Step 2. Select the MVC project template from the next “One ASP.Net wizard”.

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”.

Figure 3: Adding class to Model
public class Venue
{
#region Properties
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "ZipCode is required")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "Country is required")]
public string Country { get; set; }
public string CountryName { get; set; }
[Required(ErrorMessage = "State is required")]
public string State { get; set; }
[Required(ErrorMessage = "City is required")]
public string City { get; set; }
public float Latitude { get; set; }
public float Longitude { get; set; }
public List<Country> Countries { get; set; }
public string CountryCode { get; set; }
#endregion
}
public class Country
{
#region Properties
public int CountryId { get; set; }
public string CountryName { get; set; }
public string MapReference { get; set; }
public string CountryCode { get; set; }
public string CountryCodeLong { get; set; }
#endregion
}
Step 2. Add a new class as named “CountryModel” and add the following code.
public class CountryModel
{
#region DatabaseMethod
public List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
List<T> Temp = new List<T>();
try
{
List<string> columnsNames = new List<string>();
foreach (DataColumn DataColumn in datatable.Columns)
{
columnsNames.Add(DataColumn.ColumnName);
}
Temp = datatable.AsEnumerable()
.ToList()
.ConvertAll<T>(row => getObject<T>(row, columnsNames));
return Temp;
}
catch
{
return Temp;
}
}
public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
string value = "";
PropertyInfo[] Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
value = row[columnname].ToString();
if (!string.IsNullOrEmpty(value))
{
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString();
objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
}
}
return obj;
}
catch
{
return obj;
}
}
#endregion
SqlConnection con;
SqlDataAdapter adap;
DataTable dt;
SqlCommand cmd;
public CountryModel()
{
string conn = ConfigurationManager.ConnectionStrings["CountryConnectionString"].ConnectionString;
con = new SqlConnection(conn);
}
public List<Country> GetCountries()
{
List<Country> countries = new List<Country>();
try
{
con.Open();
adap = new SqlDataAdapter();
dt = new DataTable();
cmd = new SqlCommand("GetCountries", con)
{
CommandType = CommandType.StoredProcedure
};
adap.SelectCommand = cmd;
adap.Fill(dt);
countries = ConvertTo<Country>(dt);
}
catch (Exception x)
{
// Handle exception
}
finally
{
cmd.Dispose();
con.Close();
}
return countries;
}
}
Step 3. Open “Web.Config” and add the following connection string code for database,
<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.
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
List<Country> objCountry = new List<Country>();
CountryModel model = new CountryModel();
objCountry = model.GetCountries();
return View(new Venue { Countries = objCountry });
}
Step 5. Now edit the “About.cshtml” page with the following code.
@model GooglePlaceMvcSample.Models.Venue
@{
ViewBag.Title = "About";
}
<h2>@ViewBag.Title</h2>
<h3>@ViewBag.Message</h3>
<p>Use this area to provide additional information.</p>
<script src="~/Scripts/jquery-2.2.3.js"></script>
<script src="~/Scripts/jquery-2.2.3.min.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.js"></script>
<script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<div class="row">
<div class="col-md-8">
<div class="form-group">
@Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "TextBoxVenueLocation" })
@Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.Id, new { @id = "EventVenueId" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.Country, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.CountryCode, new SelectList(Model.Countries, "CountryCode", "CountryName"), "Choose Country", new { @class = "selectBox form-control", @id = "DropDownListCounties" })
@Html.HiddenFor(m => m.CountryName, new { @id = "HdnCountryName" })
@Html.ValidationMessageFor(m => m.Country, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ZipCode, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control", id = "TextBoxZipCode", maxlength = 6 })
@Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.State, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.State, new { @class = "form-control", id = "TextBoxState" })
@Html.ValidationMessageFor(m => m.State, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.City, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.TextBoxFor(m => m.City, new { @class = "form-control", id = "TextBoxCity" })
@Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" })
</div>
</div>
@Html.HiddenFor(m => m.Latitude, new { @id = "EventVenueLatitude" })
@Html.HiddenFor(m => m.Longitude, new { @id = "EventVenueLongitude" })
</div>
</div>
Step 6. Open the Content-> Site.css and add the following code in the bottom.
.selectBox {
width: 295px;
height: 38px;
padding: 0 0 0 9px;
}
select option {
width: 255px;
}
Step 7. Save the application and debug it.

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”,

Figure 5: Creating New Project in Google APIs
Step 3. Enter the name for API Key as shown below,

Figure 6: Create Server API Key
Step 4. Now, you can copy your API Key from the next wizard.

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,
<add key="GooglePlaceAPIKey" value="Your API Key" />
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,





Jupiter ITechnoPosted Aug 27, 2018, 9:55 PM
I getting this error : The type or namespace name 'RequiredAttribute' could not be found (are you missing a using directive or an assembly reference?)
Jupiter ITechnoPosted Aug 27, 2018, 10:20 AM
Hello , I want the code for getting city,state,country by entering only pincode in textbox.
Ali HacterPosted Jul 8, 2018, 5:38 PM
Can you please share with me working source code on my Gmail Account [email protected] will be appreciated.
Mohammad Nasir UddinPosted Oct 28, 2017, 4:14 AM
@Nimit Joshi, Thank you very much for the post. It's an excellent article. Is there any download address of the code.
monty edwardsPosted Aug 18, 2017, 12:11 PM
Where is the Database? Should have the EF code here as well, since I am not sure how to generate it, anyone have a GitHub repo of this?
David ReganPosted Jun 26, 2017, 11:17 AM
Hi guys if anyone has the solution to the url problem that was already posted below could you please post? Thanks.
Krishna VeniPosted Jun 2, 2017, 3:09 AM
How to get the database for this sample?
Delpin Susai RajPosted Aug 28, 2016, 12:01 PM
Good
Blocked AccountPosted Jun 20, 2016, 1:30 AM
Nice Article
Nimit JoshiPosted Jun 20, 2016, 12:51 AM
farooq smd How you added URL in WebConfig: Add like this: <add key="GooglePlaceAPIUrl" value="https://maps.googleapis.com/maps/api/place/autocomplete/json?input={0}&types=geocode&language=en&key={1}"/>
farooq smdPosted Jun 17, 2016, 9:50 AM
error
farooq smdPosted Jun 17, 2016, 9:49 AM
when i add in app setting it showing type ,language ,key not defined
farooq smdPosted Jun 17, 2016, 9:48 AM
where we can add this GooglePlaceAPIUrl in webconfig file
Santhakumar MunuswamyPosted Jun 9, 2016, 12:31 AM
Thank you for well written
Nimit JoshiPosted Jun 7, 2016, 10:53 AM
Thanks all
Vignesh ManiPosted Jun 7, 2016, 7:00 AM
Good article
Gowtham KPosted Jun 7, 2016, 1:23 AM
Great Article, Thanks for sharing:)
Thiruppathi RPosted Jun 7, 2016, 1:18 AM
Your article is very useful for me ,Thanks joshi
Debasis SahaPosted Jun 7, 2016, 12:52 AM
Nice share..
RajaPosted Jun 7, 2016, 12:27 AM
Nice Share....