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.
- CREATE TABLE [dbo].[GoogleMap](
- [ID] [int] IDENTITY(1,1) NOT NULL,
- [CityName] [nvarchar](50) NULL,
- [Latitude] [numeric](18, 0) NULL,
- [Longitude] [numeric](18, 0) NULL,
- [Description] [nvarchar](100) NULL,
- CONSTRAINT [PK_GoogleMap] PRIMARY KEY CLUSTERED
- (
- [ID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- CREATE procedure [dbo].[spAddNewLocation]
- (
- @CityName nvarchar(50),
- @Latitude numeric(18, 0),
- @Longitude numeric(18, 0),
- @Description nvarchar(100)
- )
- as
- begin
- insert into [dbo].[GoogleMap](CityName,Latitude,Longitude,Description)
- values(@CityName,@Latitude,@Longitude,@Description)
- end
-
- CREATE procedure [dbo].[spGetMap]
- as
- begin
- select CityName,Latitude,Longitude,Description from [dbo].[GoogleMap]
- end
Screenshot of database table with inserted data.
Step 2
Open visual studio 2015 or your choice and click on New Project.
Screenshot for creating new project-1
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
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
Step 3
Double click on webconfig file in created project and add the following line of code for database connection.
- <connectionStrings>
- <add name="DBCS" connectionString="data source=DESKTOP-M021QJH\SQLEXPRESS; database=MvcDemoDB; integrated security=true;" />
- </connectionStrings>
Step 4
Right click on Models folder in project solution explorer; select Add, then select Class.
Screenshot for creating Model class-1
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
Write a class field and properties as we have done in the database table.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace MvcGoogleMap_Demo.Models
- {
- public class Locations
- {
- public int ID { get; set; }
- [Required(ErrorMessage ="Please enter city name")]
- [Display(Name ="City Name")]
- public string CityName { get; set; }
- [Required(ErrorMessage = "Please enter city latitude")]
- public double Latitude { get; set; }
- [Required(ErrorMessage = "Please enter city longitude ")]
- public double Longitude { get; set; }
- public string Description { get; set; }
- }
- }
Step 5
Right click on Controllers folder select Add then choose Controller as shown in the below screenshot.
After clicking on controller a window will appear choose MVC5 Controller-Empty an click on Add.
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.
Add the following namespace in controller
- using MvcGoogleMap_Demo.Models;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
Create action method with name Location to get data.
- public ActionResult Location()
- {
- string markers = "[";
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetMap", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader sdr = cmd.ExecuteReader();
- while (sdr.Read())
- {
- markers += "{";
- markers += string.Format("'title': '{0}',", sdr["CityName"]);
- markers += string.Format("'lat': '{0}',", sdr["Latitude"]);
- markers += string.Format("'lng': '{0}',", sdr["Longitude"]);
- markers += string.Format("'description': '{0}'", sdr["Description"]);
- markers += "},";
- }
- }
- markers += "];";
- ViewBag.Markers = markers;
- return View();
- }
Create action method with name Location to insert data.
- public ActionResult Location(Locations location)
- {
- if (ModelState.IsValid)
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewLocation", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@CityName", location.CityName);
- cmd.Parameters.AddWithValue("@Latitude", location.Latitude);
- cmd.Parameters.AddWithValue("@Longitude", location.Longitude);
- cmd.Parameters.AddWithValue("@Description", location.Description);
- cmd.ExecuteNonQuery();
- }
- }
- else
- {
-
- }
- return RedirectToAction("Location");
- }
Complete code for controller
- using MvcGoogleMap_Demo.Models;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.Mvc;
-
- namespace MvcGoogleMap_Demo.Controllers
- {
- public class HomeController : Controller
- {
-
- public ActionResult Index()
- {
- return View();
- }
- public ActionResult Location()
- {
- string markers = "[";
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spGetMap", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- SqlDataReader sdr = cmd.ExecuteReader();
- while (sdr.Read())
- {
- markers += "{";
- markers += string.Format("'title': '{0}',", sdr["CityName"]);
- markers += string.Format("'lat': '{0}',", sdr["Latitude"]);
- markers += string.Format("'lng': '{0}',", sdr["Longitude"]);
- markers += string.Format("'description': '{0}'", sdr["Description"]);
- markers += "},";
- }
- }
- markers += "];";
- ViewBag.Markers = markers;
- return View();
- }
- [HttpPost]
- public ActionResult Location(Locations location)
- {
- if (ModelState.IsValid)
- {
- string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
- using (SqlConnection con = new SqlConnection(CS))
- {
- SqlCommand cmd = new SqlCommand("spAddNewLocation", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@CityName", location.CityName);
- cmd.Parameters.AddWithValue("@Latitude", location.Latitude);
- cmd.Parameters.AddWithValue("@Longitude", location.Longitude);
- cmd.Parameters.AddWithValue("@Description", location.Description);
- cmd.ExecuteNonQuery();
- }
- }
- else
- {
-
- }
- return RedirectToAction("Location");
- }
- }
- }
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.
Step 7
Click on Tools, select NuGet Package Manager, then choose Manage NuGet Packages for Solution and click on it.
After that a window will appear. Choose Browse type bootstrap and install package in project as shown.
Similarly type JQuery and install latest version of JQuery package in project and jquery validation file from NuGet then close NuGet Solution.
Keep require bootstrap and jQuery file and delete remaining file if not using. Or you can download from and add in project.
Step 8
Add required script and style in head section of view.
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API "></script>
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="~/scripts/jquery.validate.min.js"></script>
- <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
- <script type="text/javascript">
- var markers = @Html.Raw(ViewBag.Markers);
- window.onload = function () {
- var mapOptions = {
- center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
- zoom: 4,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var infoWindow = new google.maps.InfoWindow();
- var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
- for (i = 0; i < markers.length; i++) {
- var data = markers[i]
- var myLatlng = new google.maps.LatLng(data.lat, data.lng);
- var marker = new google.maps.Marker({
- position: myLatlng,
- map: map,
- title: data.title
- });
- (function (marker, data) {
- google.maps.event.addListener(marker, "click", function (e) {
- infoWindow.setContent(data.description);
- infoWindow.open(map, marker);
- });
- })(marker, data);
- }
- }
- </script>
Complete view code
- @model MvcGoogleMap_Demo.Models.Locations
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>Location</title>
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
- <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API Key"></script>
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
- <script src="~/scripts/jquery-3.3.1.min.js"></script>
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="~/scripts/jquery.validate.min.js"></script>
- <script src="~/scripts/jquery.validate.unobtrusive.min.js"></script>
- <script type="text/javascript">
- var markers = @Html.Raw(ViewBag.Markers);
- window.onload = function () {
- var mapOptions = {
- center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
- zoom: 4,
- mapTypeId: google.maps.MapTypeId.ROADMAP
- };
- var infoWindow = new google.maps.InfoWindow();
- var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
- for (i = 0; i < markers.length; i++) {
- var data = markers[i]
- var myLatlng = new google.maps.LatLng(data.lat, data.lng);
- var marker = new google.maps.Marker({
- position: myLatlng,
- map: map,
- title: data.title
- });
- (function (marker, data) {
- google.maps.event.addListener(marker, "click", function (e) {
- infoWindow.setContent(data.description);
- infoWindow.open(map, marker);
- });
- })(marker, data);
- }
- }
- </script>
- </head>
- <body>
- @using (Html.BeginForm("Location", "Home", FormMethod.Post))
- {
- <div class="container py-4">
- <h5 class="text-center">HOW TO CREATE GOOGLE MAP AND ADD LOCATION DYNAMICALLY USING ASP.NET MVC 5</h5>
- <div class="card">
- <div class="card-header bg-danger">
- <h6 class="card-title text-uppercase text-white">Google Map Location</h6>
- </div>
- <div class="card-body">
- <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>
-
- <div class="modal fade" id="myMap">
- <div class="modal-dialog modal-lg">
- <div class="modal-content">
- <div class="modal-header">
- <h4 class="modal-title">Add New Location</h4>
- <button type="button" class="close" data-dismiss="modal">×</button>
- </div>
- <div class="modal-body">
- <div class="row">
- <div class="col-sm-4 col-md-4 col-xs-12">
- <div class="form-group">
- <label>City Name:</label>
- @Html.EditorFor(model =>model.CityName, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.CityName, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="col-sm-4 col-md-4 col-xs-12">
- <div class="form-group">
- <label>Latitude:</label>
- @Html.EditorFor(model => model.Latitude, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Latitude, "", new { @class = "text-danger" })
- </div>
- </div>
- <div class="col-sm-4 col-md-4 col-xs-12">
- <div class="form-group">
- <label>Longitude:</label>
- @Html.EditorFor(model => model.Longitude, new { htmlAttributes = new { @class = "form-control" } })
- @Html.ValidationMessageFor(model => model.Longitude, "", new { @class = "text-danger" })
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-sm-12 col-md-12 col-xs-12">
- <div class="form-group">
- <label>Description:</label>
- <textarea name="Description" rows="5" class="form-control"></textarea>
- @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
- </div>
- </div>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-danger rounded-0" data-dismiss="modal">Close</button>
- <button class="btn btn-primary rounded-0">Submit</button>
- </div>
- </div>
- </div>
- </div>
- <div id="dvMap" class="card" style="width: 100%; height: 400px">
- </div>
- </div>
- </div>
- </div>
- }
- </body>
- </html>
Step 9
Build and Run Project ctrl + F5
Screenshot of Final output-1
Screenshot of Final output-2
Screenshot of Final output-3
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.