How to integrate Google Maps using angular js in MVC 5 application ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Monday, 27 June 2016

How to integrate Google Maps using angular js in MVC 5 application

23:14:00 Posted by raviteja swayampu , 4 comments
Hello every one thank for your support.Today i came with another real time concept "Integrating Google maps in ASP.NET MVC5 web applications".In previous days we find the contact details in any company or organisation contact pages but now the things are changed.Now we are searching any address through google maps.So,There is a need to integrate map address of our organisation or to show the identity many of the site are sharing their address in the maps and displaying in their websites.
The above is main reason for integrating Maps in websites.Now in this tutorial i am going to explain How to integrate Google Maps in our MVC 5 web application using Angular js.For this Google provides Map API for this problem.we can easily integrate it in our application by passing Coordinates(latititude and Langitude).
The application final output is like below screen shot..

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 on 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 following columns.
CREATE TABLE [dbo].[Locations] (
    [LocationID] INT           IDENTITY (1, 1) NOT NULL,
    [Title]      VARCHAR (100) NOT NULL,
    [Lat]        VARCHAR (10)  NOT NULL,
    [Long]       VARCHAR (10)  NOT NULL,
    [Address]    VARCHAR (200) NOT NULL,
    [ImagePath]  VARCHAR (200) NOT NULL,
    PRIMARY KEY CLUSTERED ([LocationID] ASC)
);

Step 4: Add Entity Data Model.

1.Go to Solution Explorer -->Right Click on 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 following code...
 public class HomeController : Controller
    {
        //This action displays Maps information
        public ActionResult Index()
        {
            return View();
        }
        //GetAllLocation - for fetch all the location from database and show in the view
        //Shows all the locations in default map here.
        public JsonResult GetAllLocation()
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = dc.Locations.OrderBy(a => a.Title).ToList();
                return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
        //This method gets the markers info from database.
        public JsonResult GetMarkerData(int locationID)
        {
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                Location l = null;
                l = dc.Locations.Where(a => a.LocationID.Equals(locationID)).FirstOrDefault();
                return new JsonResult { Data = l, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
            }
        }
    }

Step 6: Add Script files to the application

1.Add another script file for writing angular scripts there.
2.Replace it with below code..
var app = angular.module('myapp', ['uiGmapgoogle-maps']); //dependency we should add to angular application
app.controller('mapsController', function ($scope, $http) {
    //this is default coordinates for the map when it loads for first time
    $scope.map = { center: { latitude: 17.406278, longitude: 78.469060 }, zoom: 16 }
    $scope.markers = [];
    $scope.locations = [];
    //to get all the locations from the server
    $http.get('/home/GetAllLocation').then(function (data) {
        $scope.locations = data.data;
    }, function () {
        alert('Error');
    });
    //service that gets makers info from server
    $scope.ShowLocation = function (locationID) {
        $http.get('/home/GetMarkerData', {
            params: {
                locationID: locationID
            }
        }).then(function (data) {
            $scope.markers = [];
            $scope.markers.push({
                id: data.data.LocationID,
                coords: { latitude: data.data.Lat, longitude: data.data.Long },
                title: data.data.title,     //title of the makers
                address: data.data.Address,     //Address of the makers
                image : data.data.ImagePath     //image --optional
            });
            //set map focus to center
            $scope.map.center.latitude = data.data.Lat;
            $scope.map.center.longitude = data.data.Long;
        }, function () {
            alert('Error'); //shows error if connection lost or error occurs
        });
    }
    //Show or Hide marker on map using options passes here
    $scope.windowOptions = {
        show: true
    };
});
3.Here ,Every thing i explained using comments in code.I think you can easily understand by seeing them.
Add Angular Reference files to project in Index page or _Layout page.
4.we can use either CDN links or can install using Nuget Package Manager console.
Using Nuget:


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

Step 7:Add Index view for UI

1.Add view to the Index action method.And replace below code
<div ng-app="myapp" ng-controller="mapsController">
    <!--It displays the markers links-->
    <div class="locations">
        <ul>
            <li ng-repeat="l in locations" ng-click="ShowLocation(l.LocationID)"><a href="#">{{l.Title}}</a></li>
        </ul>
    </div>
    <div class="maps">
        <!-- Add directive code (gmap directive) for show map and markers-->
        <ui-gmap-google-map style="box-shadow:2px 2px 2px 2px lightgrey" center="map.center" zoom="map.zoom">
            <ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
                <ui-gmap-window options="windowOptions" show="windowOptions.show">
                    <div style="max-width:200px">
                        <div class="header"><strong>{{marker.title}}</strong></div>
                        <div id="mapcontent">
                            <p>
                                <img ng-src="{{marker.image}}" style="width:200px; height:100px" />
                                <div>{{marker.address}}</div>
                            </p>
                        </div>
                    </div>
                </ui-gmap-window>
            </ui-gmap-marker>
        </ui-gmap-google-map>
    </div>
</div>

Styles for Maps:
.angular-google-map-container {
        height: 300px;
        box-shadow:2px 2px 3px 3px lightgrey;
    }
    .angular-google-map {
        width: 80%;
        height: 100%;
        margin: auto 0px;
    }
Finally run the application and see the output in browser ..

Download code of this application here Source code 

Conclusion

I hope this tutorial may helpful for a every reader and you learn how to integrate it in MVC application.Please subscribe and follow this blog for daily updates..


4 comments:

  1. Gracias, es lo que estaba buscando...

    ReplyDelete
  2. Great Post.It is very helpful. It might help too http://www.code-sample.com/2015/06/google-maps-in-angularjs.html

    ReplyDelete
  3. How can i add new marker and save its Lang and Lat to database

    ReplyDelete