2 回答
TA贡献1995条经验 获得超2个赞
确保在加载 Google Maps API 后初始化地图。要做到这一点,只需将callbackgoogle 的 url 的一部分指向将处理它的函数(参见下面的示例)。
同样,正如 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>
添加回答
举报