Rich Whitfield
Rich Whitfield

Reputation: 153

Google maps InfoWindow not opening on click event

I am having some problems with google maps api (v3) and InfoWindows no opening on the marker's click event that they are attached to. When I debug the javascript the Markers and InfoWindows look to have been created correctly, so I am assuming that I am doing something wrong when adding the click event listener.

Below is where the adding of Markers etc happens. Can anyone see what the problem may be?

$.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"
         );

Thanks for any suggestions,

Rich

Upvotes: 3

Views: 11347

Answers (1)

Rich Whitfield
Rich Whitfield

Reputation: 153

I finally solved it in the by having a function outside the post function that creates an InfoWindow and adds a click listener to a marker to open the 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);
    });
}

It seems that you need a separate function to add multiple InfoWindows as seen here

Event Closures

Cheers

Rich

Upvotes: 11

Related Questions