谷歌地图InfoWindow没有在点击事件上打开

时间:2011-02-08 12:34:40

标签: javascript google-maps-api-3

我在google maps api(v3)和InfoWindows上遇到了一些问题,因为它们附加到标记的点击事件上没有打开。当我调试javascript时,Markers和InfoWindows看起来已经正确创建,所以我假设我在添加click事件监听器时做错了。

下面是添加标记等的地方。任何人都可以看到问题所在吗?

$.post("/Club/SearchClubsByLocation", { latitude: searchLat, longitude: searchLng },
            function (clubs) {
                $.each(clubs, function (i, club) {
                    var LL = new google.maps.LatLng(club.Latitude, club.Longitude);
                    pointArray.push(LL);

                    var infoWindow = new google.maps.InfoWindow({
                        content: club.ClubName + " HELLO!!!"
                    });

                    var marker = new google.maps.Marker({
                        map: map,
                        position: LL
                    });

                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.open(map, marker);
                    });

                    markerArray.push(marker);
                });

                for (i in pointArray) {
                    bounds.extend(pointArray[i]);
                }

                map.fitBounds(bounds);
                pointArray = [];
            },
            "json"
         );

感谢您的任何建议,

1 个答案:

答案 0 :(得分:10)

我终于通过在post函数之外创建了一个函数来解决它,它创建了一个InfoWindow并向标记添加了一个点击监听器来打开InfoWindow

$.post("/Club/SearchClubsByLocation", { latitude: searchLat, longitude: searchLng },
  function (clubs) {
    $.each(clubs, function (i, club) {
      var LL = new google.maps.LatLng(club.Latitude, club.Longitude);
      pointArray.push(LL);

      var marker = new google.maps.Marker({
        map: map,
        position: LL
      });

      addInfoWindow(marker, club.ClubName);

      markerArray.push(marker);
    });

    for (i in pointArray) {
      bounds.extend(pointArray[i]);
    }

    map.fitBounds(bounds);
    pointArray = [];
  },
  "json"
);

function addInfoWindow(marker, content) {
    var infoWindow = new google.maps.InfoWindow({
        content: content
    });

    google.maps.event.addListener(marker, 'click', function () {
        infoWindow.open(map, marker);
    });
}

似乎您需要一个单独的函数来添加多个InfoWindows,如此处所示

Event Closures

干杯