javascript - 向 Google map 添加多个标记

标签 javascript asp.net-mvc google-maps

我正在尝试向 Google map 添加多个标记。我正在使用 .NET MVC 4,我正在将 ViewModel 传递给带有包含所有坐标的数组的 View 。我想将所有这些显示到 Google map 中。该数组在 ViewModel 中命名为 latLngCoordinates。

@model Project.Web.ViewModels.ParkingViewModel

出错的代码:

for (var i = 0; i < @Model.latLngCoordinates.Length; i++) {
            addMarker(@Model.latLngCoordinates[i]);
}

错误:名称“i”在当前上下文中不存在。

这段代码工作正常:

<script type="text/javascript"
  src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
    function initialize() {
        var mapOptions = {
            center: new google.maps.LatLng(51.92479, 4.469833),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map"),
        mapOptions);

        for (var i = 0; i < @Model.latLngCoordinates.Length; i++) {
            addMarker(51.918769, 4.480616);
        }

        function addMarker(x, y) {
            var location = new google.maps.LatLng(x, y);
            var marker = new google.maps.Marker({
                position: location,
                map: map,
            });
        }

    } google.maps.event.addDomListener(window, 'load', initialize);
</script>

如果我使用:

addMarker(@Model.latLngCoordinates[1])

或任何其他高达 97 的值都有效..

最佳答案

您正在将 JavaScript 与 C# 混为一谈。这是 Razor View 上的常见错误。

你的for循环是JavaScript,所以i是JavaScript的一个变量。您的 latLngCoordinates 数组来自 C#,因此它们没有直接关系。

@for (var i = 0; i < Model.latLngCoordinates.Length; i++) {
    Html.Raw("addMarker(" + Model.latLngCoordinates[i] + "); ");
}

这使您的 for 语句成为 C# 代码。所以现在,i 与模型的数组相关联。当您在 latLngCoordinates 长度上时,它将打印许多 addMarker 函数。

关于javascript - 向 Google map 添加多个标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17195950/

相关文章:

javascript - Datejs 与以前的日期有关的问题

javascript - Socket.IO 客户端在回来时接收离线消息

asp.net-mvc - 用于 restful api 的 MVC .net

c# - 路径存在的 MVC 路由

ios - 如何在 GMSMapView 上实现 GMSMarker 拖放?

javascript - 为谷歌地图中的每个标记分配信息窗口

javascript - 使用链接 rel ="import"将 SVG 加载到页面中

javascript - 当我将操作传递给 mapDispatchToProps 时,为什么 this.props 未定义?

c# - 如何在 Html.TextBoxFor 中使用 ShortDate 字符串格式

javascript - 是否有任何 gmap 的 api 函数来连接 AddressDetails 结构中的地址字符串?