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

ASP.NET Core 6 MVC集成地图:实现附近清真寺查询功能遇阻

ASP.NET Core 6 MVC 集成Google地图实现附近清真寺查找

一、先修复前端代码的语法问题

你当前的代码存在未闭合函数、代码块的问题,且缺少地图初始化的完整逻辑,修正后的完整前端代码如下:

<div id="map" style="width: 100%; height: 500px;"></div>

@section Scripts {
    <!-- 直接在API链接中指定回调函数,确保地图加载完成后执行初始化 -->
    <script src="https://maps.googleapis.com/maps/api/js?key=你的GoogleAPI密钥&callback=initMap" async defer></script>
    <script>
        let mapInstance;

        function initMap() {
            // 尝试获取用户当前位置
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    // 获取位置成功
                    (position) => {
                        const userCoords = {
                            lat: position.coords.latitude,
                            lng: position.coords.longitude
                        };
                        // 以用户位置为中心初始化地图
                        mapInstance = new google.maps.Map(document.getElementById("map"), {
                            center: userCoords,
                            zoom: 15,
                            mapTypeId: 'roadmap'
                        });
                        // 添加用户位置标记
                        new google.maps.Marker({
                            position: userCoords,
                            map: mapInstance,
                            title: "你的位置",
                            icon: { url: "https://maps.gstatic.com/mapfiles/ms/icons/blue-dot.png" }
                        });
                        // 加载并展示附近清真寺
                        loadMosques(userCoords);
                    },
                    // 获取位置失败时的降级处理
                    (error) => {
                        const defaultCenter = { lat: 37.12, lng: 102 };
                        mapInstance = new google.maps.Map(document.getElementById("map"), {
                            center: defaultCenter,
                            zoom: 15
                        });
                        alert("无法获取你的位置,已使用默认地图中心");
                        loadMosques(defaultCenter);
                    }
                );
            } else {
                alert("你的浏览器不支持地理定位功能");
            }
        }

        // 从后端获取清真寺数据并在地图上标记
        async function loadMosques(userCoords) {
            try {
                const response = await fetch('/Mosque/GetNearbyMosques');
                const mosques = await response.json();
                
                mosques.forEach(mosque => {
                    const mosqueCoords = {
                        lat: parseFloat(mosque.latitude),
                        lng: parseFloat(mosque.longitude)
                    };
                    // 创建清真寺标记
                    const marker = new google.maps.Marker({
                        position: mosqueCoords,
                        map: mapInstance,
                        title: mosque.name
                    });
                    // 创建点击标记显示的信息窗口
                    const infoWindow = new google.maps.InfoWindow({
                        content: `
                            <div style="padding:8px;">
                                <h4>${mosque.name}</h4>
                                <p>${mosque.information || '暂无介绍'}</p>
                                ${mosque.image ? `<img src="${mosque.image}" style="width:160px; height:auto; margin-top:8px;" />` : ''}
                            </div>
                        `
                    });
                    // 绑定标记点击事件
                    marker.addListener('click', () => infoWindow.open(mapInstance, marker));
                });
            } catch (err) {
                console.error('加载清真寺数据失败:', err);
                alert('无法加载清真寺信息,请稍后重试');
            }
        }
    </script>
}

二、后端配套实现

1. 完善Mosque模型

如果你的location字段是字符串格式(比如"37.12,102"),建议拆分出单独的经纬度字段,方便前端直接使用:

public class Mosque
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Location { get; set; } // 保留原字段(如果需要)
    public double Latitude { get; set; } // 新增纬度字段
    public double Longitude { get; set; } // 新增经度字段
    public string Information { get; set; }
    public string Image { get; set; } // 图片路径或URL
}

2. 添加Mosque控制器API

创建MosqueController,提供获取清真寺数据的接口(实际开发中需从数据库读取,这里用模拟数据示例):

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

public class MosqueController : Controller
{
    // 模拟数据库数据,实际替换为EF Core查询
    private readonly List<Mosque> _mockMosques = new()
    {
        new Mosque 
        { 
            Id = 1, 
            Name = "市中心清真寺", 
            Latitude = 37.1215, 
            Longitude = 102.002, 
            Information = "建于1995年,可容纳500人礼拜", 
            Image = "/images/mosque-center.jpg" 
        },
        new Mosque 
        { 
            Id = 2, 
            Name = "城西清真寺", 
            Latitude = 37.118, 
            Longitude = 101.997, 
            Information = "历史古寺,具有传统建筑风格", 
            Image = "/images/mosque-west.jpg" 
        }
    };

    // 返回清真寺数据的API接口
    [HttpGet]
    public IActionResult GetNearbyMosques()
    {
        // 实际开发中可根据用户位置计算距离,筛选附近的清真寺
        var responseData = _mockMosques.Select(m => new
        {
            m.Id,
            m.Name,
            m.Latitude,
            m.Longitude,
            m.Information,
            m.Image
        });
        return Json(responseData);
    }

    // 地图页面的Action
    public IActionResult MapPage()
    {
        return View();
    }
}

三、关键注意事项

  • 替换代码中的你的GoogleAPI密钥为有效的Google Maps JavaScript API密钥,确保已在Google Cloud控制台启用该API
  • 地理定位功能需要HTTPS环境,本地开发可启用ASP.NET Core的HTTPS调试
  • 实际生产环境中,需根据用户位置计算距离,筛选附近的清真寺(可使用Haversine公式计算两点距离,或用数据库的地理空间查询)

内容的提问来源于stack exchange,提问作者Med EDDAHBY

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:17:29