timpone
timpone

Reputation: 19979

Google maps - not sure why I am always getting the first infowindow

I have the following code and everytime I click on one of the markers, I get the first infowindow. I have 181 infowindows and 181 markers. Any help appreciated.

var i=0;
$.each(in_locations,function(k,v){
  console.log(v);
  var marker_latlng = new google.maps.LatLng(v.latitude, v.longitude);


   markers[i] = new google.maps.Marker({
     position: marker_latlng,
     map: map, 
     title:"here is my title" + v.id
   });


   infowindows[i] = new google.maps.InfoWindow({
     content: "here is some content string" + v.id,
   });

  google.maps.event.addListener(markers[i], 'click', function() {
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
    infowindows[i].open(map,markers[i]);
  });
  i++;
});

thx

Upvotes: 0

Views: 82

Answers (2)

Luca Filosofi
Luca Filosofi

Reputation: 31173

UPDATED

$.each(in_locations, function(i, item){
  console.log(i);
  var marker_latlng = new google.maps.LatLng(item.latitude, item.longitude);


   var markers = new google.maps.Marker({
     position: marker_latlng,
     map: map, 
     title:"here is my title" + item.id
   });


   var infowindows = new google.maps.InfoWindow({
     content: "here is some content string" + item.id,
   });

  google.maps.event.addListener(markers, 'click', function() {
    alert('number of infowindows: ' + in_locations.length + ' and value is: ' + i);
    infowindows.open(map, markers);
  });
});
  • explanation? you are already inside a loop $.each so you don't need to increment an i++ iterator

Upvotes: 2

david
david

Reputation: 18288

Does the alert tell you that the value is always 181? You need to wrap your handler declaration in a closure to stop it using the external value of i (which will always be 181 once the loop completes)

  (function(i){
    google.maps.event.addListener(markers[i], 'click', function() {
      alert('number of infowindows: ' + infowindows.length + ' and value is: ' + i);
      infowindows[i].open(map,markers[i]);
    });
  }(i));

Edit: Because you're using jQuery's $.each function, which gives each iteration its own scope (because each iteration is calling a function) you can also get around your issue by creating a local variable, say j, which grabs the external value of i.

  var j = i;
  google.maps.event.addListener(markers[i], 'click', function() {
    alert('number of infowindows: ' + infowindows.length + ' and value is: ' + j);
    infowindows[j].open(map,markers[j]);
  });

(This works because every iteration a new j is created, whereas before you only had 1 i because you declared it outside the iterating function.)

Upvotes: 2

Related Questions