【发布时间】:2021-02-01 00:32:52
【问题描述】:
我正在 ASP.NET MVC Core 中创建一个项目,我正在尝试创建一个带有坐标的列表并在它旁边显示一个谷歌地图图钉。
地图正在渲染,但显示为灰色/空白。
我的地图列表代码
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Coordinates)
</th>
</tr>
</thead>
<tbody>
@{
int count = 0;
}
@foreach (var item in Model)
{
<tr>
<td>
<div id="@count" style="height:400px;width:700px;"></div>
<script type="text/javascript">myMap('@count', @item.Coordinates)</script>
@Html.DisplayFor(modelItem => item.Coordinates)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Coordinates">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Coordinates">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Coordinates">Delete</a>
</td>
</tr>
count++;
}
</tbody>
</table>
我正在使用的 JS 函数。它与我的 API 密钥一起加载到 head 中
<script type="text/javascript">
function myMap(divId, coord) {
var myCenter = new google.maps.LatLng(coord);
var mapProp = { center: myCenter, zoom: 12, scrollwheel: false, draggable: true, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById(divId), mapProp);
var marker = new google.maps.Marker({ position: myCenter });
marker.setMap(map);
}
</script>
这是我的结果。
当我不在 for 循环中加载地图并使用脚本但使用硬编码参数时,它可以正常工作。
<div id="googleMap" style="height:400px;width:100%;"></div>
<script>
function myMap() {
var myCenter = new google.maps.LatLng(@Model.Coordinates);
var mapProp = { center: myCenter, zoom: 12, scrollwheel: false, draggable: true, mapTypeId: google.maps.MapTypeId.ROADMAP };
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({ position: myCenter });
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=myMap"></script>
我无法弄清楚我做错了什么,我一直在寻找但找不到任何答案。任何帮助表示赞赏!
【问题讨论】:
-
您不能以数字开头。您的循环看起来像是用数字命名 div 的 id。例如,尝试在数字前加上 map_。
-
是的,我一定会试一试的。
标签: javascript c# asp.net-core google-maps-api-3 razor-pages