In this article I will explain with an example, how to bind
Leaflet maps from
SQL Server database in ASP.Net Core 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 two classes:
Location
This model class is used in DbContext class for fetching data from database using
Entity Framework.
public class Location
{
[Key]
public string Name { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string Description { get; set; }
}
MarkerModel
This model class is used for populating the Leaflet maps.
public class MarkerModel
{
public string Title { get; set; }
public string Description { get; set; }
public decimal Lat { get; set; }
public decimal Lng { get; set; }
}
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace Bind_Leaflets_Maps_Core_MVC
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Location> Locations { get; set; }
}
}
Namespaces
You will need to import the following namespaces.
using Newtonsoft.Json
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
SerializeObject method of
JsonConvert class and set to a
ViewBag object.
public class HomeController : Controller
{
private DBCtx Context { get; set; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
List<MarkerModel> markers = new List<MarkerModel>();
foreach (Location location in this.Context.Locations)
{
markers.Add(new MarkerModel
{
Title = location.Name,
Description = location.Description,
Lat = location.Latitude,
Lng = location.Longitude
});
}
ViewBag.Markers = JsonConvert.SerializeObject(markers);
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: 400px; height: 400px;"></div>
</body>
</html>
Screenshot
Demo
Downloads