繁体   English   中英

使用 SQL 数据库和 Leaflet Map 在 Z9E0DA8438E1E38B81CDD3

[英]Display Marker Using Latitude And Longitude From SQL Database With Leaflet Map In ASP.NET CORE MVC

对于我的网站,我在 Visual Studios 2019 上使用 ASP.net Core MVC,在我的数据库中使用 SQL Server Management Studio。

我正在尝试使用数据库中的数据(纬度和经度)将标记显示到 Leaflet map 上。 我遇到了一个为此提供解决方案的网站。 但是,它使用的是 ASP.net 而不是 Asp.net 内核。

我必须更改代码的哪些部分才能让它在我身边工作?

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        
    }  
}

看法:

@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>  

据我所知,如果您想从 asp.net mvc 迁移到 asp.net 核心 mvc,这很容易。

您首先应该确保您知道如何在 asp.net 内核中使用 EF 内核。

您应该首先在 asp.net 内核中创建一个 model 并创建 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; }
}

然后您可以使用 VS 管理控制台并输入:

add-migration initialcreate
update-database

然后在startup.cs中添加以下代码:

        services.AddDbContext<TestDbcontext>();

在 MVC controller 中:

公共 class HomeController: Controller { 私有只读 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
        //    });

 
        };
    }
    
}

查看 html:

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

    <script src="https://unpkg.com/leaflet@1.6.0/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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM