0

for my website, I am using ASP.net Core MVC on Visual Studios 2019 and SQL Server Management Studio for my database.

I am trying to display markers using data(Latitude and Longitude) from my Database onto a Leaflet map. I came across a website providing a solution for this. However, it was using ASP.net instead of Asp.net Core.

Which parts of the code do I have to change for it to work on my side?

Controller:

using System;    
using System.Collections.Generic;    
using System.Data;    
using System.Data.Entity;    
using System.Linq;    
using System.Net;    
using System.Web;    
using System.Web.Mvc;    
using WebApplication1.Models;    
    
    
namespace WebApplication1.Controllers    
{    
    public class MapsController : Controller    
    {    
        private test2Entities db = new test2Entities();    
    
        // GET: Maps    
        public ActionResult Index()    
        {    
            return View(db.Maps.ToList());    
        }    
  
        #region [Map]    
        [HttpPost]    
        public JsonResult GetMap()    
        {    
            var data1 = Map();    
            return Json(data1, JsonRequestBehavior.AllowGet);    
        }    
        public IEnumerable<Map> Map()    
        {    
            return (from p in db.Maps    
                    select new    
                    {    
                        Name = p.Name,    
                        Latitude = p.Latitude,    
                        Longitude = p.Longitude,    
                        Location = p.Location,    
                        Description = p.Description,    
                        Id = p.Id    
                    }).ToList()    
                .Select(res => new Map    
                {    
                    Name = res.Name,    
                    Latitude = res.Latitude,    
                    Longitude = res.Longitude,    
                    Location = res.Location,    
                    Description = res.Description,    
                    Id = res.Id        
                });        
        }    
        #endregion        
    }  
}

View:

@model IEnumerable<WebApplication1.Models.Map>    
    
@{    
    Layout = null;    
}    
    
<link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />    
<script type='text/javascript' src='http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js?2'></script>    
    
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>    
    
<div id="map" style="height: 440px; border: 1px solid #AAA;"></div>    
    
<script type="text/javascript">    
    
$(document).ready(function () {    
    var map = L.map('map', {    
    
        center: [10.1102278, 77.8958904],    
          minZoom: 4,    
          zoom: 6    
    });    
                $.ajax({    
                    type: "POST",    
                    url: '/Maps/GetMap',    
                    success: function (data) {    
                        var result = JSON.stringify(data);    
    
                        for (var i = 0; i < result.length; ++i) {    
                            var popup ='<b>Name:</b> '+ data[i].Name +    
                            '<br/><b>Latitude:</b> ' + data[i].Latitude +    
                              '<br/><b>Longitude:</b> ' + data[i].Longitude+    
                           '<br/><b>Location:</b> ' + data[i].Location;    
    
    
                            L.marker([data[i].Latitude, data[i].Longitude])    
                                .bindPopup(popup)    
                               .addTo(map);    
                        }    
    
                    },    
                    error: function (xhr) {    
    
                        console.log(xhr.responseText);    
                        alert("Error has occurred..");    
                    }    
                });    
    
                L.tileLayer('http://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', {    
                    attribution: '© <a href="http://osm.org/copyright" title="OpenStreetMap" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="http://www.mapquest.com/" title="MapQuest" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',    
                    subdomains: ['otile1', 'otile2', 'otile3', 'otile4']    
                }).addTo(map);    
    
            });    
    
</script>  

2 Answers 2

1

As far as I know, if you want to migrate from asp.net mvc to asp.net core mvc, it's easily.

You should firstly make sure you have know how to use EF core in asp.net core.

You should firstly create a model in asp.net core and create the dbcontext:

public class TestDbcontext: DbContext
{
    public DbSet<Map> Documents { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {

        optionsBuilder.UseSqlServer(@"Your connection string");
    }

}

Map class:

public class Map
{
    public string Name { get; set; }
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string Location { get; set; }
    public string Description { get; set; }
    public string Id { get; set; }
}

Then you could use VS management console and type in:

add-migration initialcreate
update-database

Then add below codes in startup.cs :

        services.AddDbContext<TestDbcontext>();

In MVC controller:

public class HomeController : Controller { private readonly ILogger _logger;

    private TestDbcontext _dbContext;

    public HomeController(ILogger<HomeController> logger, TestDbcontext dbContext)
    {
        _logger = logger;
        _dbContext = dbContext;
    }

    public IActionResult ShowMap()
    {
        return View(_dbContext.Maps.ToList());
    }

    [HttpPost]
    public IActionResult GetMap()
    {
        var data1 = Map();
        return Json(data1);
    }

    public IEnumerable<Map> Map()
    {
        //return (from p in _dbContext.Maps
        //        select new
        //        {
        //            Name = p.Name,
        //            Latitude = p.Latitude,
        //            Longitude = p.Longitude,
        //            Location = p.Location,
        //            Description = p.Description,
        //            Id = p.Id
        //        }).ToList()
        //    .Select(res => new Map
        //    {
        //        Name = res.Name,
        //        Latitude = res.Latitude,
        //        Longitude = res.Longitude,
        //        Location = res.Location,
        //        Description = res.Description,
        //        Id = res.Id
        //    });

 
        };
    }
    
}

View html:

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ShowMap</title>
</head>
<body>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
          integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
          crossorigin="" />

    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
            integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
            crossorigin=""></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>

    <div id="map" style="height: 440px; border: 1px solid #AAA;"></div>

    <script type="text/javascript">


        $(document).ready(function () {
            var map = L.map('map', {

                center: [10.1102278, 77.8958904],
                minZoom: 4,
                zoom: 6
            });
            $.ajax({
                type: "POST",
                url: '/Default/GetMap',
                success: function (data) {
                    var result = JSON.stringify(data);

                    for (var i = 0; i < result.length; ++i) {
                        var popup = '<b>Name:</b> ' + data[i].Name +
                            '<br/><b>Latitude:</b> ' + data[i].Latitude +
                            '<br/><b>Longitude:</b> ' + data[i].Longitude +
                            '<br/><b>Location:</b> ' + data[i].Location;


                        L.marker([data[i].Latitude, data[i].Longitude])
                            .bindPopup(popup)
                            .addTo(map);
                    }

                },
                error: function (xhr) {

                    console.log(xhr.responseText);
                    alert("Error has occurred..");
                }
            });

            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="http://osm.org/copyright" title="OpenStreetMap" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="http://www.mapquest.com/" title="MapQuest" target="_blank">MapQuest</a> <img src="http://developer.mapquest.com/content/osm/mq_logo.png" width="16" height="16">',
             }).addTo(map);

     
        });

    </script>
</body>
</html>
2
  • Hi, thank you for your answer. However, I forgot to mention that my map isn't showing. It would only display the frame with a blank screen inside. I think there is something wrong with the View code. How do i solve it?
    – addsw
    Commented Jul 8, 2020 at 7:24
  • Where is the definition of Maps? Commented Jul 21, 2022 at 9:47
0

It's a bit late, but I ran into the same issue. I needed to add a tile Layer to the map (I used OpenStreetMap) to get the map to display something in the frame. Adding this here as an answer in case someone else gets here with the same question:

<script>
   const map = L.map('map').setView([30.0000,-81.0000], 8);
   L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
      maxZoom: 19,
      attribution: '&copy; 
         <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a>'
   }).addTo(map);
</script>

Not the answer you're looking for? Browse other questions tagged or ask your own question.