ASP.net Core Dynamically Adding markers on Leaflet Map [closed]

天涯浪子 提交于 2021-01-29 06:08:13

问题


How do I display markers dynamically on a Leaflet Map using ASP.net Core MVC and SQL Server on a website?


回答1:


Here is a whole demo like below:

Model:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string LName { get; set; }
}

View(Note:data[i].propertyName,the property name should be camel case):

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

@section Scripts
{
    <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 type="text/javascript">
        $(document).ready(function () {           
            var map = L.map('map', {
                center: [46.674590, 9.276266],
                minZoom: 4,
                zoom: 6
            });
            $.ajax({
                type: "POST",
                url: '/Tests/Index',
                success: function (data) {
                        var result = JSON.stringify(data);

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

                            L.marker([data[i].name, data[i].lName])
                                .bindPopup(popup)
                                .addTo(map);
                        }
                       },
                error: function (xhr) {
                    alert("Error has occurred..");
                }
            });
 
            L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
        });
    </script>
}

Controller:

public class TestsController : Controller
{
    private readonly YourDbContext _context;

    public TestsController(YourDbContext context)
    {
        _context = context;
    }

    // GET: Tests
    public IEnumerable<Test> Index()
    {
        return _context.Test.ToList();
    }
}

Database:

Result:



来源:https://stackoverflow.com/questions/62780481/asp-net-core-dynamically-adding-markers-on-leaflet-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!