Search code examples
google-mapsgoogle-maps-api-3infowindowmarkerclusterer

Markerclusterer and infowindow v3 is not working properly


I have used the sample code from google for markerclusterer. I added a code to display the coordinate of the marker in an infowindow for the markerclusterer v3 but the problem is it only loads the last marker latlang into the window: Can anyone help to resolve this issue.

  function initialize() {
    var center = new google.maps.LatLng(37.4419, -122.1419);
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

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

    var markers = [];
    for (var i = 0; i < 100; i++) {
      var dataPhoto = data.photos[i];
      var latLng = new google.maps.LatLng(dataPhoto.latitude,
          dataPhoto.longitude);
      var info = dataPhoto.photo_id;
      var marker = new google.maps.Marker({
        position: latLng


      });

    google.maps.event.addListener(marker, 'click', function() {

    infowindow.setPosition(latLng);
    infowindow.setContent(latLng.toString()); 

    infowindow.open(map,marker);


    });
      markers.push(marker);

    }



    var markerCluster = new MarkerClusterer(map, markers);
  }


  google.maps.event.addDomListener(window, 'load', initialize);

  var infowindow = new google.maps.InfoWindow(
  { 
  size: new google.maps.Size(150,50)
  });

</script>`

Solution

  • Here I found the answer using the hint @geocodezip provided. The event addListener should be changed as follows:

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(marker.position.toString());
          infowindow.open(map, marker);
        }
      })(marker, i));