Auto Complete Address Using Google API In ASP.NET MVC

Many times as a programmer we have to work with address fields; rather than giving a simple textbox you can make it more user friendly by using Google API. We can create an auto address complete field using google API.
 
Here we will use Google API for auto complete Address field in our ASP.NET MVC 5 application.
 
Step 1: Let's create an ASP.NET MVC application, select MVC template and click on OK.
 
 
 
Step 2: Right click on Project, click Add, then New Item. Go to Data, select ADO.NET Entity Data Model and give name Model1.
 
 
 
 
 
Step 3: Select 'EF Designer from database' and click on Next.
 
 
 
Step 4: From the Connection Properties select your Database, Enter User Id and Password to make a connection with Employee data table.
 
 
 
Step 5: From the next dialog, click on 'Yes' and then Next, it will generate the connection string in web.config file.
 
 
 
Step 6: Select your Database Object and Settings, select Table Employee and click Finish
 
 
 It will create your Model.edmx, now build your application.
 
 
 
Step 7: Now right click on Controllers, Add, then click Controller.
 
 
Step 8: Select MVC 5 Controller with views, using Entity Framework.
 
 
 
Step 9: From the next dialog, select Employee Model class, and select EmpEntities from Data context class and click OK
 
 
 
Step 10: Scaffolding will create your views: Create, Edit, View, Delete etc. Now open the Create.cshtml file and add THE following script in @section Scripts
  1. <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>  
  2. <script type="text/javascript">  
  3.         google.maps.event.addDomListener(window, 'load', function () {  
  4.             var options = {  
  5.                 types: ['(cities)'],  
  6.                 componentRestrictions: { country: "in" }  
  7.             };  
  8.   
  9.             var input = document.getElementById('Address');  
  10.             var places = new google.maps.places.Autocomplete(input, options);  
  11.   
  12.   
  13.         });  
  14. </script>  
Two things are important here, which i highlighted in below screen,
  • In componentRestrictions you can set the Search Restrictions to country specific, so here it will display only India(in)'s Address, and
  • In getElementbyId we can pass the model's field name which is Address Field. 
 
 
 
 
 
Step 11: Save your changes and run your application, now start typing address in Address textbox and it will auto suggest the address to user.  
 
 
 
You can add the same script in Edit.cshtml also to make sure the auto address suggestion works in Edit mode also.
 
 
 
I hope you liked this article.
 
Read more articles on ASP.NET:


Similar Articles