In this article I will explain with an example, how to integrate, populate and display Google Maps V3 from database in ASP.Net MVC 5 Razor.
The database records consisting of Latitude and Longitude information will be used to integrate Google Maps with multiple markers in ASP.Net MVC 5 Razor.
Database
Following is the schema of the Locations Table which will store the Cities and their Geographical Locations.
The Table has been inserted records with Longitude and Latitude information of three different cities, along with their names and descriptions.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Configuration;
Controller
The Controller consists of the Index Action method. Inside this Action method, the records are fetched from the Locations Table using ADO.Net in ASP.Net MVC 5 Razor.
Google Maps need an array of Markers which consists of Name, Latitude, Longitude and Description and hence a JavaScript Array is built from the fetched Location records with the help of string concatenation.
The generated string is assigned to a ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string markers = "[";
string conString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
SqlCommand cmd = new SqlCommand("SELECT * FROM Locations");
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
markers += "{";
markers += string.Format("'title': '{0}',", sdr["Name"]);
markers += string.Format("'lat': '{0}',", sdr["Latitude"]);
markers += string.Format("'lng': '{0}',", sdr["Longitude"]);
markers += string.Format("'description': '{0}'", sdr["Description"]);
markers += "},";
}
}
con.Close();
}
markers += "];";
ViewBag.Markers = markers;
return View();
}
}
View
The View consists of an HTML DIV element which will be used for loading and displaying the Google Map.
Note: In order to execute the Google Maps application you will need to register and get an API key from Google API. For more details refer here.
The Array of Markers (built inside the Controller) is read from the ViewBag object using Html.Raw Helper function.
The markers array built inside the Controller is assigned to the markers JavaScript variable. Then inside the JavaScript Window OnLoad event handler, first the Google Maps is displayed inside the HTML DIV element and then using a loop, marker is plotted on the map for each City present in the array.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API_Key"></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: 8,
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>
</body>
</html>
Screenshot
Downloads