In this article I will explain with an example, how to bind
Leaflet maps from
SQL Server database in ASP.Net MVC.
Database
I have made use of the following table Locations with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model consists of following properties:
public class MarkerModel
{
public string Title { get; set; }
public string Description { get; set; }
public decimal Lat { get; set; }
public decimal Lng { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, a Generic List of MarkerModel class is created
A FOR EACH loop is executed over the
Location class and the records i.e.
title,
latitude,
longitude and
description from the
Locations Table are fetched using
Entity Framework and added to the Generic List of
MarkerModel class object.
Finally, the object of Generic List of
MarkerModel class is serialized using
Serialize method of
JavaScriptSerializer class and set to a
ViewBag object.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<MarkerModel> mapData = new List<MarkerModel>();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Locations", con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
mapData.Add(new MarkerModel
{
Title = sdr["Name"].ToString(),
Lat = Convert.ToDecimal(sdr["Latitude"]),
Lng = Convert.ToDecimal(sdr["Longitude"]),
Description = sdr["Description"].ToString()
});
}
}
con.Close();
}
}
ViewBag.Markers = (new JavaScriptSerializer()).Serialize(mapData);
return View();
}
}
Script for Implementing JavaScript Leaflet Library
Inside the HTML, the following Leaflet CSS file is inherited.
1. leaflet.css
And then, the following Leaflet JS file is inherited.
1. leaflet.js
Inside the
window.onload function, an array of markers of different geographic address locations fetched from the Controllers Action method is defined using
ViewBag object named as
Markers.
The Html.Raw helper method is used to set the details in an array as it helps to prevent automatically encoding of special characters.
The Leaflet map is initialized using map function and default view is set using setView function in which latitude and longitude from the array of markers is passed as parameter.
Then, using titleLayer function the attribution property is set and added to the map.
A FOR EACH loop is executed over an array of markers and each marker is added to the Leaflet map using following functions:
Marker – For adding latitude and longitude.
bindPopup – For displaying title and description.
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script type="text/javascript" src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script type="text/javascript">
window.onload = function () {
var markers = eval('@Html.Raw(ViewBag.Markers)');
// Initializing the Map.
var map = L.map('dvMap').setView([markers[0].Lat, markers[0].Lng], 8);
// Setting the Attribution.
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Adding Marker to map.
markers.forEach(function (item) {
L.marker([item.Lat, item.Lng])
.bindPopup("<b>" + item.Title + "</b><br />" + item.Description).addTo(map);
});
};
</script>
View
The view consists of an HTML DIV element for displaying Leaflet maps.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet"href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script type="text/javascript"src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script type="text/javascript">
window.onload = function () {
var markers = eval('@Html.Raw(ViewBag.Markers)');
// Initializing the Map.
var map = L.map('dvMap').setView([markers[0].Lat, markers[0].Lng], 8);
// Setting the Attribution.
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Adding Marker to map.
markers.forEach(function (item) {
L.marker([item.Lat, item.Lng])
.bindPopup("<b>" + item.Title + "</b><br />" + item.Description).addTo(map);
});
};
</script>
</head>
<body>
<div id="dvMap" style="width: 500px; height: 500px"></div>
</body>
</html>
Screenshot
Demo
Downloads