如何从Razor调用JavaScript函数?Google Maps标记未加载求助
问题分析与解决方案
看起来你遇到的核心问题是ShowLocation函数从未被调用,甚至可能调用了但因为报错没执行成功。我帮你梳理下两个最可能的原因,以及对应的修复方案:
1. Razor变量未正确传递到JavaScript
你在Razor循环里写的ShowLocation(lattitude, longitude),这里的lattitude和longitude是C#变量,但你没有用@符号输出它们的值,导致JavaScript会把它们当成未定义的变量,直接报错中断脚本执行,自然ShowLocation就没被调用。
2. 脚本执行时机不对
你的map对象是在window.onload里初始化的,但Razor循环输出的脚本是页面加载过程中就执行的,这时候map还没创建出来——就算ShowLocation被调用了,也会因为找不到map对象而报错。
修复后的完整代码示例
@model AccountViewModel <script type="text/javascript"> // 定义数组存储所有单车的位置数据 var bicycleLocations = []; function ShowLocation(lt, lng) { var googleLatLong = new google.maps.LatLng(lt, lng); var markerOptions = { position: googleLatLong, map: map, clickable: true }; new google.maps.Marker(markerOptions); } // 地图初始化逻辑(整合你的原有window.onload代码) window.onload = function() { // 这里替换成你原来的地图初始化配置 var mapOptions = { center: new google.maps.LatLng(39.9042, 116.4074), // 示例:北京坐标 zoom: 12 }; // 全局map变量,确保ShowLocation能访问到 window.map = new google.maps.Map(document.getElementById("map"), mapOptions); // 地图初始化完成后,批量添加标记 bicycleLocations.forEach(function(pos) { ShowLocation(pos.lat, pos.lng); }); }; </script> <div> <h2>Bicycle Locations</h2> </div> <div id="map" class="col-md-8 col-sm-6"> Map Loading.... </div> @foreach (var bicycle in Model.Bicycles) { if (bicycle.LastLocationID != 0) { var location = Model.LastKnowLocations.FirstOrDefault(l => l.ID == bicycle.LastLocationID); // 增加null判断,避免空引用报错 if (location != null) { <script type="text/javascript"> // 用@输出C#变量到JavaScript数组 bicycleLocations.push({ lat: @location.Latitude, lng: @location.Longitude }); </script> } } }
额外注意事项
- 确保你已经在页面中正确加载了Google Maps API脚本(比如在
<head>里添加带有你的API密钥的脚本标签)。 - 打开浏览器开发者工具(F12)的控制台,查看有没有报错信息——这是排查前端脚本问题最快的方式,比如API加载失败、变量未定义等都会在这里显示。
- 把
map挂载到window对象上,确保ShowLocation函数能全局访问到它。
内容的提问来源于stack exchange,提问作者Kurt
相关产品推荐
相关产品推荐

