标记上的事件监听器不起作用(不会触发)

时间:2019-05-12 21:55:59

标签: javascript google-maps google-maps-markers infowindow

我使用Ajax调用控制器来获取lng&lat数组,然后根据其地理位置将标记放置在地图上。我还为每个标记创建了infoWindow,然后将其附加到地图上。但是,如果我在Ajax内(特别是在$ .each内)添加事件监听器,则在尝试打开infoWindow时仅触发最后一个标记。

我试图将其放在Ajax方法之外,这样可以侦听所有标记,但根本不起作用。

我做错了什么?这是我的代码

var contentString;
var infowindow;
var map;
var marker;
function initMap() {
    var trLatLng = new google.maps.LatLng(51.509865, -0.118092);
    var options = {
        center: trLatLng,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('tradesmenMap'), options);

}

 $.ajax({
     url: '@Url.Action("GetTradesmen", "TradesmanNearYou")',
     type: "GET",
     contentType: "JSON",
     data: { tr: 'Tradesman' },
     success: function (tradesman) {

         console.log(tradesman);
         $.each(tradesman, function (i, tr) {

             contentString = '<div class="container">' +
                 '<div class="row">' +
                 '<h1 id="tradesmanHeading" class="firstHeading">' + tr.FullName + '</h1>' +
                 '<div id="col-sm-12">' +

                 '<p> <a href="https://en.wikipedia.org/w/index.php?title=Uluru&oldid=297882194">' +
                 'https://en.wikipedia.org/w/index.php?title=Uluru</a> ' +
                 '</p>' +
                 '</div>' +
                 '</div>' +
                 '</div>';

                 infowindow = new google.maps.InfoWindow({
                 content: contentString
             });

             marker = new google.maps.Marker({
                 position: new google.maps.LatLng(tr.Lattitude, tr.Longtitude),
                 title: tr.FullName,
                 animation: google.maps.Animation.DROP,
                 map: map
             });
         });
     }
});    
marker.addListener('click', function () {
    infowindow.open(map, marker);
});

0 个答案:

没有答案
相关问题