Google 在 for 循环中通过函数调用时地图无法正确呈现

Google map not rendering properly when called via function in a for loop

我正在 ASP.NET MVC Core 中创建一个项目,我正在尝试创建一个带有坐标的列表并在其旁边显示一个 google 地图图钉。

地图正在渲染,但呈灰色 out/blank。

我的地图列表代码

<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>

我不知道我做错了什么,我一直在寻找但找不到任何答案。感谢您的帮助!

确保在加载 Google 地图 API 后初始化地图。为此,只需将 google 的 url 的 callback 部分指向将处理它的函数(参见下面的示例)。

正如 Lee 在他的评论中所说,不要使用数字作为元素 ID。 Lee 关于使用前缀的建议很准确,您应该考虑使用它。

<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 class="map" id="map_@count" style="height:400px;width:700px;" data-coord="@item.Coordinates"></div>
                    <!-- REMOVED script here and added more data to the div element above -->
                    @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>
<script>
  // this function will be called by google's api once loaded
  function loaded() {
    // assuming each map container has a class "map",
    let maps = document.querySelectorAll('.map');
    maps.forEach(map => initMap(map));
  }
  function initMap(map) {
    var myCenter = new google.maps.LatLng(map.dataset.coord); // retrieving coords from data attribute
    var mapProp = { center: myCenter, zoom: 12, scrollwheel: false, draggable: true, mapTypeId: google.maps.MapTypeId.ROADMAP };
    var map = new google.maps.Map(map, 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=loaded"></script>

编辑:看看下面的代码片段。我之前没有发现坐标必须作为数字传递。

let maps = document.querySelectorAll('.map')

function loaded() {
  maps.forEach(map => initMap(map))
}

function initMap(element) {
  let xy = element.dataset.coords.split(',').map(a => parseFloat(a))
  let center = new google.maps.LatLng(xy[0], xy[1])
  let props = { center: center, zoom: 12, scrollwheel: false, draggable: true, mapTypeId: google.maps.MapTypeId.ROADMAP };
  let map = new google.maps.Map(element, props);
  let marker = new google.maps.Marker({ position: center });
  marker.setMap(map);
}
.map {
  width: 400px;
  height: 400px;
  background: yellow;
  margin-bottom: 15px;
}
<!-- The British Museum -->
<div class="map" data-coords="51.5145532,-0.1167918"></div>
<!-- Castello Sforzesco -->
<div class="map" data-coords="45.4636261,9.1714131"></div>
<!-- Nordscheleife -->
<div class="map" data-coords="50.3341015,6.9404738"></div>

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=loaded" async defer></script>

也许你在地图初始化之前得到了坐标?尝试在 OnMapReady 事件

中进行 api 调用