How To Implement A Google Map And Add Location Dynamically Using MVC 5

Introduction

This article will demonstrate how to create a Google map and add location dynamically by inserting latitude and longitude of a location. I will save the name of the location, latitude, longitude and some description about location in SQL server database table. I will call saved data through JavaScript and display it in the Google map.

Step 1

Open MS SQL server 2014 or choice create database table.

  1. CREATE TABLE [dbo].[GoogleMap](  
  2.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [CityName] [nvarchar](50) NULL,  
  4.     [Latitude] [numeric](18, 0) NULL,  
  5.     [Longitude] [numeric](18, 0) NULL,  
  6.     [Description] [nvarchar](100) NULL,  
  7.  CONSTRAINT [PK_GoogleMap] PRIMARY KEY CLUSTERED   
  8. (  
  9.     [ID] ASC  
  10. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  11. ON [PRIMARY]  
  12.   
  13. GO  
  14.   
  15. CREATE procedure [dbo].[spAddNewLocation]  
  16. (  
  17. @CityName nvarchar(50),  
  18. @Latitude numeric(18, 0),  
  19. @Longitude numeric(18, 0),  
  20. @Description nvarchar(100)  
  21. )  
  22. as  
  23. begin  
  24. insert into [dbo].[GoogleMap](CityName,Latitude,Longitude,Description)  
  25. values(@CityName,@Latitude,@Longitude,@Description)  
  26. end  
  27.   
  28. CREATE procedure [dbo].[spGetMap]  
  29. as  
  30. begin  
  31. select CityName,Latitude,Longitude,Description from [dbo].[GoogleMap]  
  32. end  

Screenshot of database table with inserted data.

MVC

Step 2

Open visual studio 2015 or your choice and click on New Project.

Screenshot for creating new project-1

MVC

 

After that one window will appear; select web from left panel choose ASP.NET Web Application, give a meaningful name to your project then click on OK as shown in the below screenshot.

Screenshot for creating new project-2

MVC

 

After clicking on OK one more window will appear choose Empty check on MVC checkbox and click on OK as shown in the below screenshot.

Screenshot for creating new project-3

MVC

 

Step 3

Double click on webconfig file in created project and add the following line of code for database connection. 

  1. <connectionStrings>  
  2.     <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=MvcDemoDB; integrated security=true;" />  
  3. </connectionStrings>  

Step 4

Right click on Models folder in project solution explorer;  select Add, then select Class.

Screenshot for creating Model class-1

MVC

 

After selecting class click on it. One window will appear, choose class and give it the name Locations then click on Add. A class will be added under models folder with name Locations.cs as shown in the below screenshot.

Screenshot for creating Model class-1

MVC

 

Write a class field and properties as we have done in the database table.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel.DataAnnotations;    
  4. using System.Linq;    
  5. using System.Web;    
  6.     
  7. namespace MvcGoogleMap_Demo.Models    
  8. {    
  9.     public class Locations    
  10.     {    
  11.         public int ID { getset; }    
  12.         [Required(ErrorMessage ="Please enter city name")]    
  13.         [Display(Name ="City Name")]    
  14.         public string CityName { getset; }    
  15.         [Required(ErrorMessage = "Please enter city latitude")]    
  16.         public double Latitude { getset; }    
  17.         [Required(ErrorMessage = "Please enter city longitude ")]    
  18.         public double Longitude { getset; }    
  19.         public string Description { getset; }    
  20.     }    
  21. } 

Step 5

Right click on Controllers folder select Add then choose Controller as shown in the below screenshot.

MVC

 

After clicking on controller a window will appear choose MVC5 Controller-Empty an click on Add.

MVC

After clicking on Add another window will appear with DefaultController. Change the name HomeController then click on Add. HomeController will be added under Controllers folder. See the below screenshot.

MVC

 

Add the following namespace in controller

  1. using MvcGoogleMap_Demo.Models;    
  2. using System.Configuration;    
  3. using System.Data;    
  4. using System.Data.SqlClient; 

Create action method with name Location to get data.

  1. public ActionResult Location()  
  2. {  
  3.     string markers = "[";  
  4.     string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  5.     using (SqlConnection con = new SqlConnection(CS))  
  6.     {  
  7.         SqlCommand cmd = new SqlCommand("spGetMap", con);  
  8.         cmd.CommandType = CommandType.StoredProcedure;  
  9.         con.Open();  
  10.         SqlDataReader sdr = cmd.ExecuteReader();  
  11.         while (sdr.Read())  
  12.         {  
  13.             markers += "{";  
  14.             markers += string.Format("'title': '{0}',", sdr["CityName"]);  
  15.             markers += string.Format("'lat': '{0}',", sdr["Latitude"]);  
  16.             markers += string.Format("'lng': '{0}',", sdr["Longitude"]);  
  17.             markers += string.Format("'description': '{0}'", sdr["Description"]);  
  18.             markers += "},";  
  19.         }  
  20.     }  
  21.     markers += "];";  
  22.     ViewBag.Markers = markers;  
  23.     return View();  
  24. }  

Create action method with name Location to insert data.

  1. public ActionResult Location(Locations location)  
  2. {  
  3.     if (ModelState.IsValid)  
  4.     {  
  5.         string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;  
  6.         using (SqlConnection con = new SqlConnection(CS))  
  7.         {  
  8.             SqlCommand cmd = new SqlCommand("spAddNewLocation", con);  
  9.             cmd.CommandType = CommandType.StoredProcedure;  
  10.             con.Open();  
  11.             cmd.Parameters.AddWithValue("@CityName", location.CityName);  
  12.             cmd.Parameters.AddWithValue("@Latitude", location.Latitude);  
  13.             cmd.Parameters.AddWithValue("@Longitude", location.Longitude);  
  14.             cmd.Parameters.AddWithValue("@Description", location.Description);  
  15.             cmd.ExecuteNonQuery();  
  16.         }  
  17.     }  
  18.     else  
  19.     {  
  20.                   
  21.     }  
  22.     return RedirectToAction("Location");  
  23. }  

Complete code for controller

  1. using MvcGoogleMap_Demo.Models;    
  2. using System.Configuration;    
  3. using System.Data;    
  4. using System.Data.SqlClient;    
  5. using System.Web.Mvc;    
  6.     
  7. namespace MvcGoogleMap_Demo.Controllers    
  8. {    
  9.     public class HomeController : Controller    
  10.     {    
  11.         // GET: Home    
  12.         public ActionResult Index()    
  13.         {    
  14.             return View();    
  15.         }    
  16.         public ActionResult Location()    
  17.         {    
  18.             string markers = "[";    
  19.             string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;    
  20.             using (SqlConnection con = new SqlConnection(CS))    
  21.             {    
  22.                 SqlCommand cmd = new SqlCommand("spGetMap", con);    
  23.                 cmd.CommandType = CommandType.StoredProcedure;    
  24.                 con.Open();    
  25.                 SqlDataReader sdr = cmd.ExecuteReader();    
  26.                 while (sdr.Read())    
  27.                 {    
  28.                     markers += "{";    
  29.                     markers += string.Format("'title': '{0}',", sdr["CityName"]);    
  30.                     markers += string.Format("'lat': '{0}',", sdr["Latitude"]);    
  31.                     markers += string.Format("'lng': '{0}',", sdr["Longitude"]);    
  32.                     markers += string.Format("'description': '{0}'", sdr["Description"]);    
  33.                     markers += "},";    
  34.                 }    
  35.             }    
  36.             markers += "];";    
  37.             ViewBag.Markers = markers;    
  38.             return View();    
  39.         }    
  40.         [HttpPost]    
  41.         public ActionResult Location(Locations location)    
  42.         {    
  43.             if (ModelState.IsValid)    
  44.             {    
  45.                 string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;    
  46.                 using (SqlConnection con = new SqlConnection(CS))    
  47.                 {    
  48.                     SqlCommand cmd = new SqlCommand("spAddNewLocation", con);    
  49.                     cmd.CommandType = CommandType.StoredProcedure;    
  50.                     con.Open();    
  51.                     cmd.Parameters.AddWithValue("@CityName", location.CityName);    
  52.                     cmd.Parameters.AddWithValue("@Latitude", location.Latitude);    
  53.                     cmd.Parameters.AddWithValue("@Longitude", location.Longitude);    
  54.                     cmd.Parameters.AddWithValue("@Description", location.Description);    
  55.                     cmd.ExecuteNonQuery();    
  56.                 }    
  57.             }    
  58.             else    
  59.             {    
  60.                     
  61.             }    
  62.             return RedirectToAction("Location");    
  63.         }    
  64.     }    
  65. } 

Step 6

Right click on Location action method in controller. Add view window will appear with default Location name, click on Add as shown in the below screenshot. View will be added in views folder under Home folder.

MVC

Step 7

Click on Tools, select NuGet Package Manager, then choose Manage NuGet Packages for Solution and click on it.

MVC

After that a window will appear. Choose Browse type bootstrap and install package in project as shown.

MVC

Similarly type JQuery and install latest version of JQuery package in project and jquery validation file from NuGet then close NuGet Solution.

MVC

Keep require bootstrap and jQuery file and delete remaining file if not using. Or you can download from and add in project.

MVC

 

Step 8

Add required script and style in head section of view. 

  1. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  2.  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API "></script>  
  3.  <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  4. <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  5.  <script src="~/scripts/bootstrap.min.js"></script>  
  6.  <script src="~/scripts/jquery.validate.min.js"></script>  
  7. <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  

Get API key from below link and paste it in highlight script API

https://developers.google.com/maps/documentation/javascript/get-api-key

Write script to get data from database

  1. <script type="text/javascript">  
  2.         var markers = @Html.Raw(ViewBag.Markers);  
  3.         window.onload = function () {  
  4.             var mapOptions = {  
  5.                 center: new google.maps.LatLng(markers[0].lat, markers[0].lng),  
  6.                 zoom: 4,  
  7.                 mapTypeId: google.maps.MapTypeId.ROADMAP  
  8.             };  
  9.             var infoWindow = new google.maps.InfoWindow();  
  10.             var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);  
  11.             for (i = 0; i < markers.length; i++) {  
  12.                 var data = markers[i]  
  13.                 var myLatlng = new google.maps.LatLng(data.lat, data.lng);  
  14.                 var marker = new google.maps.Marker({  
  15.                     position: myLatlng,  
  16.                     map: map,  
  17.                     title: data.title  
  18.                 });  
  19.                 (function (marker, data) {  
  20.                     google.maps.event.addListener(marker, "click"function (e) {  
  21.                         infoWindow.setContent(data.description);  
  22.                         infoWindow.open(map, marker);  
  23.                     });  
  24.                 })(marker, data);  
  25.             }  
  26.         }  
  27.     </script>  

Complete view code

  1. @model MvcGoogleMap_Demo.Models.Locations  
  2. @{  
  3.     Layout = null;  
  4. }  
  5.   
  6. <!DOCTYPE html>  
  7.   
  8. <html>  
  9. <head>  
  10.     <meta name="viewport" content="width=device-width" />  
  11.     <title>Location</title>  
  12.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">  
  13.     <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API Key"></script>  
  14.     <link href="~/Content/bootstrap.min.css" rel="stylesheet" />  
  15.     <script src="~/scripts/jquery-3.3.1.min.js"></script>  
  16.     <script src="~/scripts/bootstrap.min.js"></script>  
  17.     <script src="~/scripts/jquery.validate.min.js"></script>  
  18.     <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>  
  19.     <script type="text/javascript">  
  20.         var markers = @Html.Raw(ViewBag.Markers);  
  21.         window.onload = function () {  
  22.             var mapOptions = {  
  23.                 center: new google.maps.LatLng(markers[0].lat, markers[0].lng),  
  24.                 zoom: 4,  
  25.                 mapTypeId: google.maps.MapTypeId.ROADMAP  
  26.             };  
  27.             var infoWindow = new google.maps.InfoWindow();  
  28.             var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);  
  29.             for (i = 0; i < markers.length; i++) {  
  30.                 var data = markers[i]  
  31.                 var myLatlng = new google.maps.LatLng(data.lat, data.lng);  
  32.                 var marker = new google.maps.Marker({  
  33.                     position: myLatlng,  
  34.                     map: map,  
  35.                     title: data.title  
  36.                 });  
  37.                 (function (marker, data) {  
  38.                     google.maps.event.addListener(marker, "click"function (e) {  
  39.                         infoWindow.setContent(data.description);  
  40.                         infoWindow.open(map, marker);  
  41.                     });  
  42.                 })(marker, data);  
  43.             }  
  44.         }  
  45.     </script>  
  46. </head>  
  47. <body>  
  48.     @using (Html.BeginForm("Location""Home", FormMethod.Post))  
  49.     {  
  50.         <div class="container py-4">  
  51.             <h5 class="text-center">HOW TO CREATE GOOGLE MAP AND ADD LOCATION DYNAMICALLY USING ASP.NET MVC 5</h5>  
  52.             <div class="card">  
  53.                 <div class="card-header bg-danger">  
  54.                     <h6 class="card-title text-uppercase text-white">Google Map Location</h6>  
  55.                 </div>  
  56.                 <div class="card-body">  
  57.                     <button style="margin-bottom:10px;" type="button" data-target="#myMap" data-toggle="modal" class="btn btn-danger btn-sm rounded-0"><i class="fa fa-plus-circle"></i> Add New Location</button>  
  58.   
  59.                     <div class="modal fade" id="myMap">  
  60.                         <div class="modal-dialog modal-lg">  
  61.                             <div class="modal-content">  
  62.                                 <div class="modal-header">  
  63.                                     <h4 class="modal-title">Add New Location</h4>  
  64.                                     <button type="button" class="close" data-dismiss="modal">×</button>  
  65.                                 </div>  
  66.                                 <div class="modal-body">  
  67.                                     <div class="row">  
  68.                                         <div class="col-sm-4 col-md-4 col-xs-12">  
  69.                                             <div class="form-group">  
  70.                                                 <label>City Name:</label>                                                
  71.                                                 @Html.EditorFor(model =>model.CityName, new { htmlAttributes = new { @class = "form-control" } })  
  72.                                                 @Html.ValidationMessageFor(model => model.CityName, ""new { @class = "text-danger" })  
  73.                                             </div>  
  74.                                         </div>  
  75.                                         <div class="col-sm-4 col-md-4 col-xs-12">  
  76.                                             <div class="form-group">  
  77.                                                 <label>Latitude:</label>  
  78.                                                 @Html.EditorFor(model => model.Latitude, new { htmlAttributes = new { @class = "form-control" } })  
  79.                                                 @Html.ValidationMessageFor(model => model.Latitude, ""new { @class = "text-danger" })  
  80.                                             </div>  
  81.                                         </div>  
  82.                                         <div class="col-sm-4 col-md-4 col-xs-12">  
  83.                                             <div class="form-group">  
  84.                                                 <label>Longitude:</label>  
  85.                                                 @Html.EditorFor(model => model.Longitude, new { htmlAttributes = new { @class = "form-control" } })  
  86.                                                 @Html.ValidationMessageFor(model => model.Longitude, ""new { @class = "text-danger" })  
  87.                                             </div>  
  88.                                         </div>  
  89.                                     </div>  
  90.                                     <div class="row">  
  91.                                         <div class="col-sm-12 col-md-12 col-xs-12">  
  92.                                             <div class="form-group">  
  93.                                                 <label>Description:</label>  
  94.                                                 <textarea name="Description" rows="5" class="form-control"></textarea>  
  95.                                                 @Html.ValidationMessageFor(model => model.Description, ""new { @class = "text-danger" })  
  96.                                             </div>  
  97.                                         </div>  
  98.                                     </div>                                    
  99.                                 </div>  
  100.                                 <div class="modal-footer">  
  101.                                     <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>  
  102.                                     <button class="btn btn-primary rounded-0">Submit</button>  
  103.                                 </div>  
  104.                             </div>  
  105.                         </div>  
  106.                     </div>  
  107.                     <div id="dvMap" class="card" style="width: 100%; height: 400px">  
  108.                     </div>  
  109.                 </div>  
  110.             </div>  
  111.         </div>  
  112.     }  
  113. </body>  
  114. </html>  

Step 9

Build and Run Project ctrl + F5

Screenshot of Final output-1

MVC

Screenshot of Final output-2

MVC

Screenshot of Final output-3

MVC

 

Conclusion

In this article, I have explained how we integrated a Google map in mvc5 using Google API key dynamically.

We can add city name, latitude and longitude by clicking on Add New Location button. We have understand step by step. I hope it will be useful in your upcoming projects.


Similar Articles