In this article I will explain with an example, how to bind
Leaflet maps from
SQL Server database in ASP.Net using C# and VB.Net.
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.
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
Adding multiple markers with InfoWindow to Leaflet Map
Inside the window.onload function, an array of markers of different geographic address locations fetched from the Controllers Action method is defined using ViewState object named as Markers.
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('<%=ViewState["Markers"].ToString()%>');
// 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>
HTML Markup
The following HTML Markup consists of:
DIV – For populating Leaflet Map.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></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('<%=ViewState["Markers"].ToString()%>');
// 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>
<form id="form1" runat="server">
<div id="dvMap" style="width: 500px; height: 500px"></div>
</form>
</body>
</html>
Public Class
The public class consists of following properties.
C#
public class MarkerModel
{
public string Title { get; set; }
public string Description { get; set; }
public decimal Lat { get; set; }
public decimal Lng { get; set; }
}
VB.Net
Public Class MarkerModel
Public Property Title As String
Public Property Description As String
Public Property Lat As Decimal
Public Property Lng As Decimal
End Class
Namespaces
You will need to import the following namespaces.
C#
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
VB.Net
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Binding Markers from Database using C# and VB.Net
Inside the Page Load event handler, the Generic List of MapModel class is created
The ExecuteReader method of SqlCommand class is executed and the records i.e. Title, Latitude, Longitude and Description from the Locations Table are fetched are inserted into a Generic List of MapModel class objects.
The object of Generic List of MapModel class is serialized using Serialize method of JavaScriptSerializer class.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
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();
}
}
ViewState["Markers"] = (new JavaScriptSerializer()).Serialize(mapData);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim mapData As List(Of MarkerModel) = New List(Of MarkerModel)()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Locations", con)
con.Open()
Using sdr As SqlDataReader = cmd.ExecuteReader()
While sdr.Read()
mapData.Add(New MarkerModel With {
.Title = sdr("Name").ToString(),
.Lat = Convert.ToDecimal(sdr("Latitude")),
.Lng = Convert.ToDecimal(sdr("Longitude")),
.Description = sdr("Description").ToString()
})
End While
End Using
con.Close()
End Using
End Using
ViewState("Markers") = (New JavaScriptSerializer()).Serialize(mapData)
End If
End Sub
Screenshot
Demo
Downloads