Google Map Using SQL Server Stored Procedure In ASP.NET MVC 5

Introduction

Google Maps is the most spectacular app through which our day-to-day life becomes easier.

The database records hold the latitude and longitude information. It will be used to populate Google Maps with multiple markers in ASP.NET MVC Razor.

Description

In this article , I will show you how to show a marker on places like country, state, continent etc., using stored procedure.

To know more details about Google Map, go through my blogs and articles related to Google Map in MVC.

http://www.c-sharpcorner.com/members/satyaprakash-samantaray

Steps to be followed are given below.

Step1

Create a table named MyPlaces.

Table Script

  1. CREATE TABLE [dbo].[MyPlaces](  
  2.     [CityName] [varchar](50) NOT NULL,  
  3.     [CityLatitude] [numeric](18, 6) NOT NULL,  
  4.     [CityLongitude] [numeric](18, 6) NOT NULL,  
  5.     [CityDescription] [varchar](300) NULL,  
  6.  CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED   
  7. (  
  8.     [CityName] ASC  
  9. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  10. ON [PRIMARY]  
  11.   
  12. GO   
Add your place name, longitude and latitude of the corresponding places with the description, as shown below.



Step 2

Create a stored procedure named Sp_GeoLoc.

Stored procedure script

  1. Create Procedure Sp_GeoLoc  
  2. As  
  3. Begin  
  4. SELECT * FROM MyPlaces  
  5. End 

Execute the stored procedure.

  1. exec Sp_GeoLoc 
 

Step 3

Create a MVC 5 Application named SatyaMVCGoogleMap.


Step 4

Put the connection string in Web.Config file.

Code ref

  1. <connectionStrings>  
  2.     <add name="ConString" connectionString="Put Your Connection String Here...."/>  
  3. </connectionStrings> 

Code description

This adds name ConString, which is important to add in controller class file to access the table and the stored procedure.

 

Step 5

Add a controller class file named HomeController.cs.

Code ref

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Configuration;  
  7. using System.Data.SqlClient;  
  8.   
  9. namespace SatyaMVCGoogleMap  
  10. {  
  11.     public class HomeController : Controller  
  12.     {  
  13.         // GET: Home  
  14.         public ActionResult Index()  
  15.         {  
  16.             string markers = "[";  
  17.             string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;  
  18.             SqlCommand cmd = new SqlCommand("Sp_GeoLoc");  
  19.             using (SqlConnection con = new SqlConnection(conString))  
  20.             {  
  21.                 cmd.Connection = con;  
  22.                 con.Open();  
  23.                 using (SqlDataReader sdr = cmd.ExecuteReader())  
  24.                 {  
  25.                     while (sdr.Read())  
  26.                     {  
  27.                         markers += "{";  
  28.                         markers += string.Format("'title': '{0}',", sdr["CityName"]);  
  29.                         markers += string.Format("'lat': '{0}',", sdr["CityLatitude"]);  
  30.                         markers += string.Format("'lng': '{0}',", sdr["CityLongitude"]);  
  31.                         markers += string.Format("'description': '{0}'", sdr["CityDescription"]);  
  32.                         markers += "},";  
  33.                     }  
  34.                 }  
  35.                 con.Close();  
  36.             }  
  37.   
  38.             markers += "];";  
  39.             ViewBag.Markers = markers;  
  40.             return View();  
  41.         }  
  42.     }  

Code description

You will need to import the namespaces given below.

  1. using System.Configuration;  
  2. using System.Data.SqlClient; 

Controller consists of the Index Action method. Inside this Action method, the records are fetched from the MyPlaces Table, using Sp_GeoLoc Stored Procedure .

Google Map needs an array of markers, which consists of CityName, CityLatitude, CityLongitude and CityDescription and hence a JavaScript Array is built from the fetched location records with the help of the string concatenation.

The generated string is assigned to a ViewBag object.

Using ADO.NET concept, I added my connection string reference add name and the stored procedure.

  1. string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;  
  2. SqlCommand cmd = new SqlCommand("Sp_GeoLoc"); 

With the help of string concatenation, all the column values are put in markers variable.

The array of markers which consists of CityName, CityLatitude, CityLongitude and CityDescription and hence a JavaScript array is built from the fetched location records with the help of string concatenation.

  1. string markers = "[";  
  2. using (SqlDataReader sdr = cmd.ExecuteReader())  
  3.                 {  
  4.                     while (sdr.Read())  
  5.                     {  
  6.                         markers += "{";  
  7.                         markers += string.Format("'title': '{0}',", sdr["CityName"]);  
  8.                         markers += string.Format("'lat': '{0}',", sdr["CityLatitude"]);  
  9.                         markers += string.Format("'lng': '{0}',", sdr["CityLongitude"]);  
  10.                         markers += string.Format("'description': '{0}'", sdr["CityDescription"]);  
  11.                         markers += "},";  
  12.                     }  
  13.                 }  
  14. markers += "];"
The generated string is assigned to a ViewBag object.
  1. ViewBag.Markers = markers; 
 
 
Step 6

Create a view named “Index.cshtml”.

Code ref & code description

In this section, I added the code description with Green commented line besides the code.

  1. @{  
  2.     ViewBag.Title = "Satyaprakash Metro City Google Map";  
  3. }  
  4.   
  5. <title>@ViewBag.Title</title> //The Title will show Here.  
  6.   
  7. <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash Google Map Using Asp.net MVC</h2>  
  8. <fieldset>  
  9.     <legend style="font-family: Arial Black; color: blue; font-size: large;">Check Metro City Using Google Map</legend>  
  10.     <div id="SatyaMap" style="width: 1240px; height: 400px;">  
  11.         @*set google map size .*@  
  12.     </div>  
  13.     <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkVZYQFe4YYva_g5ulymGDt9EBoVjjZJ8"></script> @*api key after sign in your google account.*@  
  14.     <script type="text/javascript">  
  15.         var markers = @Html.Raw(ViewBag.Markers); //all string value of column properties to viewbag.  
  16.         window.onload = function () {  
  17.             var mapOptions = {  
  18.                 center: new google.maps.LatLng(markers[3].lat, markers[3].lng), //which city will be shown.  
  19.                 zoom: 9, //google map page zoom  
  20.                 mapTypeId: google.maps.MapTypeId.ROADMAP //type of view.  
  21.             };  
  22.             var infoWindow = new google.maps.InfoWindow();  
  23.             var map = new google.maps.Map(document.getElementById("SatyaMap"), mapOptions);//pass div id and google map load values.  
  24.             for (i = 0; i < markers.length; i++) { //here load all city map name  
  25.                 var data = markers[i]  
  26.                 var myLatlng = new google.maps.LatLng(data.lat, data.lng); //here i assigned lat and long.  
  27.                 var marker = new google.maps.Marker({  
  28.                     position: myLatlng, //lat and long value  
  29.                     map: map, //div id  
  30.                     title: data.title //city name  
  31.                 });  
  32.                 (function (marker, data) { //here city map description after click on it.  
  33.                     google.maps.event.addListener(marker, "click"function (e) {  
  34.                         infoWindow.setContent(data.description); //city description value  
  35.                         infoWindow.open(map, marker); //then pop will show  the description  
  36.                     });  
  37.                 })(marker, data);  
  38.             }  
  39.         }  
  40.     </script>  
  41. </fieldset>  
  42.   
  43. <footer>  
  44.     <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@  
  45. </footer> 
Note

View consists of an HTML DIV element, which will be used to load and display Google Map.

The markers array built inside Controller are assigned to the markers JavaScript variable. Inside the JavaScript Window, OnLoad event handler, first, Google Maps are displayed inside HTML DIV element and then using a loop, marker is plotted on the map for each city present in the array.



Step 7

Set start page in “RouteConfig.cs”.

Code ref

  1. routes.MapRoute(  
  2.                 name: "Default",  
  3.                 url: "{controller}/{action}/{id}",  
  4.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  5.             );   
Code description

Here, the name of the controller is Home.

Here, name of the view or controller action method is Index.

Output

URL is http://localhost:57131/Home/Index

At first, load the page and the city is shown, as I mentioned.

  1. center: new google.maps.LatLng(markers[3].lat, markers[3].lng) 
  

All the cities with Google Markers Icon are shown, using SQL Server stored procedure.

 

We need to check for city decsription of Bengaluru, Bhubaneswar, Hyderabad, Khurdha.  
 
 
 
 
 
 
 
 
GIF image for better understanding

Summary

  1. Google map marker placements, using stored procedure.
  2. City description details.
  3. Instead of mentioning longitude and latitude in view section manually, you can get those from the database.
  4. Implement ADO.NET in ASP.NET MVC.


Similar Articles