-1

I connect to the the database and get some information as a json then I Show them when I do this it can easily recognize lan and longtitude and show them on map but when it comes to text that I return to show it when user click on the markers just one text is shown for all and it seems that it attaches the text to first marker for all other markers attach the same text what am I missing? I am totally confused!

for (var i=0; i<tweetsToPlot.length; i++){
        var lat = tweetsToPlot[i].lat;
        var lng = tweetsToPlot[i].lng;
        var myLatLng = new google.maps.LatLng(lat, lng);
        var txt=tweetsToPlot[i].text;
         var myMarker = new google.maps.Marker({
              position: myLatLng,
              title: "LatLng Feb 17",
              map:map
             }); 

        google.maps.event.addListener(myMarker, 'click', function() {
            var infowindow = new google.maps.InfoWindow({
              content: txt
            });
            infowindow.open(map, this);
          });

        var index = tweetsToPlot[i].id;
        discs[index] = myMarker;
       myMarker.setVisible(true);   
    }
}
HMdeveloper
  • 2,772
  • 9
  • 45
  • 74
  • possible duplicate of [Google Maps JS API v3 - Simple Multiple Marker Example](http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example) – geocodezip Mar 08 '14 at 23:58

1 Answers1

0

You need closures. Your myMarker variable keeps changing, so even though you've assigned the click handler to the marker, the actual reference to the marker keeps changing as you iterate through your loop.

... at least, that's what it sounds like (and the symptoms match).

(function(markerObj) {
    google.maps.event.addListener(myMarker, 'click', function() {
        var infowindow = new google.maps.InfoWindow({
            content: txt
        });
        infowindow.open(map, this);
    });
})(myMarker);
Julian H. Lam
  • 25,501
  • 13
  • 46
  • 73