You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ASP.NET MVC中用C#与SQLite在Leaflet地图添加经纬度标记

实现从SQLite读取经纬度并在Leaflet地图展示的完整流程

1. 完善后端数据访问层配置

首先确保实体模型与数据库表对应,配置DbContext以操作SQLite:

  • 创建实体模型 Local.cs:
namespace maps.Models
{
    public class Local
    {
        public int ID { get; set; }
        public double Latitude { get; set; }
        public double Longitude { get; set; }
    }
}
  • 创建DbContext类 AppDbContext.cs:
using maps.Models;
using Microsoft.EntityFrameworkCore;

namespace maps.Data
{
    public class AppDbContext : DbContext
    {
        public DbSet<Local> Locals { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlite("Data Source=mapLocations.db"); // 替换为你的SQLite数据库路径
        }
    }
}
  • 在 Program.cs 中注册DbContext:
builder.Services.AddDbContext<AppDbContext>();

2. 在Controller中查询数据并传递到View

在目标Controller的Action中读取SQLite数据,通过ViewBag或强类型模型传递到视图:

using maps.Data;
using maps.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace maps.Controllers
{
    public class HomeController : Controller
    {
        private readonly AppDbContext _context;

        public HomeController(AppDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index()
        {
            var locations = await _context.Locals.ToListAsync();
            ViewBag.Locations = locations;
            return View();
        }
    }
}

3. 在CSHTML视图中渲染Leaflet标记

修改视图脚本,将后端数据转为JS数组,循环创建地图标记:

<head>
    <!-- 引入Leaflet必要资源 -->
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
</head>
<body>
    <div id="map" style="width:700px; height:580px"></div>

    <script>
        var map = L.map('map').setView([51.5, -0.09], 13);

        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);

        // 解析后端传递的经纬度数据
        var locations = @Html.Raw(Json.Serialize(ViewBag.Locations));
        
        // 批量创建地图标记
        locations.forEach(location => {
            L.marker([location.Latitude, location.Longitude])
              .addTo(map)
              .bindPopup(`位置ID: ${location.ID}`); // 可自定义弹窗内容
        });

        var seekPlace = L.Control.geocoder().addTo(map);
    </script>
</body>

4. 测试验证

  • 通过表单向SQLite数据库添加几条测试经纬度数据
  • 运行ASP.NET MVC应用,访问对应页面,确认地图上已显示所有标记

内容的提问来源于stack exchange,提问作者João Vítor Melo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 05:45:34