简体   繁体   English

无论单击哪一个,最后一个 Google 地图标记的信息窗口都会打开

[英]Infowindow for last Google Maps marker opens no matter which one clicked

I'm trying to run the google maps api in an ASP.NET MVC project, and I'm trying to add markers with info windows on every marker.我正在尝试在 ASP.NET MVC 项目中运行谷歌地图 api,并且我正在尝试在每个标记上添加带有信息 windows 的标记。 Unfortunately, when I click on a marker, the info window on the last marker added opens, regardless of which marker I clicked.不幸的是,当我单击一个标记时,无论我单击哪个标记,最后添加的标记上的信息 window 都会打开。

Here is my code:这是我的代码:

<script>
        var map;
        function initMap() {
            map = new google.maps.Map(document.getElementById('map'), {
                center: { lat: 39.5, lng: -98.35 },
                zoom: 3
            });
            @foreach (var item in Model) {
                 <text>
                    var marker = new google.maps.Marker({
                      map: map,
                      position: { lat: @item.Lat, lng: @item.Lng },
                      title: '@item.Name'
                    });

                    marker.info = new google.maps.InfoWindow({
                        content: `<div id="content"> <h1 id="firstHeading" class="firstHeading">Test</h1> <div id="bodyContent">Test </div> </div>`
                    });

                    marker.addListener('click', function () {
                        marker.info.open(map, marker);
                    });

                </text>
}
        }
    </script>

Sorry removed previous answer..抱歉删除了以前的答案..

I just remembered I believe when I was doing my project I had to create a createWindow(marker, content) function and call it from the loop rather than actually creating my window inside of the loop directly我只记得我相信当我在做我的项目时,我必须创建一个createWindow(marker, content) function 并从循环中调用它,而不是直接在循环内创建我的 window

it is important that your eventlistener is created in this method also, not inside the loop重要的是你的事件监听器也是在这个方法中创建的,而不是在循环内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM