Integrate Google Maps Using Angular In MVC 5

Hello everyone and thanks for your support. Today, I came up with another real time concept, "Integrating Google maps in ASP.NET MVC5 Web Applications". In previous days, we found the contact details for any company on organization contact pages,  but now things have changed. Now, we can search any address through Google maps. Hence, there is a need to integrate the map address of our organization, as many of the site are sharing their address in the maps and are displaying it in their websites.

The above is the main reason to integrate maps in the websites. Now, in this tutorial, I am going to explain how to integrate Google maps in our MVC 5 Web Application,  using AngularJS. For this, Google provides Map API. We can easily integrate it in our Application by passing Coordinates (latititude and longitude).

The Application final output is shown in the screenshot, given below,

output

Step 1 - Create New Project.

Go to File --> New --> Project --> ASP.NET Web Application under Web section --> Entry Application Name --> click OK --> select Empty template --> Checked MVC -->click OK.

Step 2 - Add a Database to project.

Go to Solution Explorer --> Right Click on App_Data folder --> Add --> New item --> Select SQL Server Database under data --> Enter Database name --> Add.

Step 3 - Create a table for store data

  1. Open Database -->Right Click Table folder --> Add New Table --> Add Columns --> Save --> Enter table name --> OK.
  2. In this tutorial, I have created a table(Locations) to store the markers location data.
  3. The table contains the columns, created below:
    1. CREATE TABLE [dbo].[Locations] (  
    2. [LocationID] INT IDENTITY (1, 1) NOT NULL,  
    3. [Title] VARCHAR (100) NOT NULL,  
    4. [Lat] VARCHAR (10) NOT NULL,  
    5. [Long] VARCHAR (10) NOT NULL,  
    6. [Address] VARCHAR (200) NOT NULL,  
    7. [ImagePath] VARCHAR (200) NOT NULL,  
    8. PRIMARY KEY CLUSTERED ([LocationID] ASC)  
    9. );  

Step 4: Add Entity Data Model.

  1. Go to Solution Explorer -->right click Project name form Solution Explorer --> Add --> New item --> select ADO.net Entity Data Model under data --> Enter model name --> Add.
  2. A popup Window will come (Entity Data Model Wizard) --> select generate from database -->click Next.
  3. Chose your data connection --> select your database -->select Entity framework version(5.0 or 6.0) next --> select tables -->enter Model Namespace name-->click Finish.

Step 5: Add Controller for Index and Get Markers info

  1. Create a Controller and name it as HomeController.cs.
  2. Replace the code with the following code:
    1. public class HomeController: Controller  
    2. {  
    3.     //This action displays Maps information  
    4.     public ActionResult Index()   
    5.         {  
    6.             return View();  
    7.         }  
    8.         //GetAllLocation - for fetch all the location from database and show in the view  
    9.         //Shows all the locations in default map here.  
    10.     public JsonResult GetAllLocation()   
    11.     {  
    12.             using(MyDatabaseEntities dc = new MyDatabaseEntities())  
    13.             {  
    14.                 var v = dc.Locations.OrderBy(a => a.Title).ToList();  
    15.                 return new JsonResult  
    16.                 {  
    17.                     Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet  
    18.                 };  
    19.             }  
    20.         }  
    21.         //This method gets the markers info from database.  
    22.     public JsonResult GetMarkerData(int locationID)  
    23.     {  
    24.         using(MyDatabaseEntities dc = new MyDatabaseEntities())  
    25.         {  
    26.             Location l = null;  
    27.             l = dc.Locations.Where(a => a.LocationID.Equals(locationID)).FirstOrDefault();  
    28.             return new JsonResult  
    29.             {  
    30.                 Data = l, JsonRequestBehavior = JsonRequestBehavior.AllowGet  
    31.             };  
    32.         }  
    33.     }  
    34. }  

Step 6: Add Script files to the application

  1. Add another script file for writing Angular scripts there.
  2. Replace it with the code, given below:
    1. var app = angular.module('myapp', ['uiGmapgoogle-maps']); //dependency we should add to angular application  
    2. app.controller('mapsController', function($scope, $http)   
    3. {  
    4.     //this is default coordinates for the map when it loads for first time  
    5.     $scope.map =   
    6.       {  
    7.         center:   
    8.         {  
    9.             latitude: 17.406278,  
    10.             longitude: 78.469060  
    11.         },  
    12.         zoom: 16  
    13.     }  
    14.     $scope.markers = [];  
    15.     $scope.locations = [];  
    16.     //to get all the locations from the server  
    17.     $http.get('/home/GetAllLocation').then(function(data)  
    18.     {  
    19.         $scope.locations = data.data;  
    20.     }, function()  
    21.     {  
    22.         alert('Error');  
    23.     });  
    24.     //service that gets makers info from server  
    25.     $scope.ShowLocation = function(locationID)  
    26.     {  
    27.             $http.get('/home/GetMarkerData',  
    28.             {  
    29.                 params:  
    30.                 {  
    31.                     locationID: locationID  
    32.                 }  
    33.             }).then(function(data)  
    34.               {  
    35.                 $scope.markers = [];  
    36.                 $scope.markers.push  
    37.                 ({  
    38.                     id: data.data.LocationID,  
    39.                     coords:  
    40.                     {  
    41.                         latitude: data.data.Lat,  
    42.                         longitude: data.data.Long  
    43.                     },  
    44.                     title: data.data.title, //title of the makers  
    45.                     address: data.data.Address, //Address of the makers  
    46.                     image: data.data.ImagePath //image --optional  
    47.                 });  
    48.                 //set map focus to center  
    49.                 $scope.map.center.latitude = data.data.Lat;  
    50.                 $scope.map.center.longitude = data.data.Long;  
    51.             }, function()  
    52.             {  
    53.                 alert('Error'); //shows error if connection lost or error occurs  
    54.             });  
    55.         }  
    56.         //Show or Hide marker on map using options passes here  
    57.     $scope.windowOptions =  
    58.       {  
    59.         show: true  
    60.     };  
    61. });  
  3. Here, I explained using comments in the code. I think you can easily understand by seeing them. Add Angular Reference files to the project in Index page or _Layout page.
  4. We can use either CDN links or can install using Nuget Package Manager console.

    Using NuGet

    map

    Using CDN links
    1. @* AngularJS library *@  
    2. <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js"></script>  
    3. @* google map*@  
    4. <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>   
    5. <script src="//rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>  
    6. <script src="~/Scripts/map.js"></script>  

Step 7:Add Index view for UI

  1. Add view to the Index action method. Replace the code, given below:
    1. <div ng-app="myapp" ng-controller="mapsController">  
    2.     <!--It displays the markers links-->  
    3.     <div class="locations">  
    4.         <ul>  
    5.             <li ng-repeat="l in locations" ng-click="ShowLocation(l.LocationID)"><a href="#">{{l.Title}}</a></li>  
    6.         </ul>  
    7.     </div>  
    8.     <div class="maps">  
    9.         <!-- Add directive code (gmap directive) for show map and markers-->  
    10.         <ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey" center="map.center" zoom="map.zoom">  
    11.             <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">  
    12.                 <ui-gmap-window options="windowOptions" show="windowOptions.show">  
    13.                     <div style="max-width:200px">  
    14.                         <div class="header"><strong>{{marker.title}}</strong></div>  
    15.                         <div id="mapcontent">  
    16.                             <p>  
    17.                                 <img ng-src="{{marker.image}}" style="width:200px; height:100px" />  
    18.                                 <div>{{marker.address}}</div>  
    19.                             </p>  
    20.                         </div>  
    21.                     </div>  
    22.                 </ui-gmap-window>  
    23.             </ui-gmap-marker>  
    24.         </ui-gmap-google-map>  
    25.     </div>  
    26. </div>  

    Styles for Maps
    1. .angular-google-map-container
    2. {    
    3. height300px;    
    4. box-shadow:2px 2px 3px 3px lightgrey;    
    5. }    
    6. .angular-google-map 
    7. {    
    8. width80%;    
    9. height100%;    
    10. marginauto 0px;    
    11. }    

Finally, run the Application and see the output in the Browser.

output

Download source code for this application here Source code
 
Conclusion

I hope this tutorial is helpful for every reader and you learn how to integrate it into the MVC Application.
See this tutorial in my blog(for reference) Integrating google maps in asp.net mvc using angular js.
 


Similar Articles