Artur Stary
Artur Stary

Reputation: 744

Key in for loop has an unexpected value

I have a simple google map with multiple markers (4 in this case). I want to add a "bubble" on click event. Markers are rendered fine, but the bubble (infowindow) show always on the last pin. I mean:

I click marker[1] - infowindow shows up on marker[3] I click marker[[2] - infowindow shows up on marker[3] etc.

I think that the problem is in the way I loop my array

Here is my loop, that iterates through 4 elements of array:

 var key = 0;
 var markers = new Array();
 var infowindows = new Array();

 for(key in myJson.hotels)
    {
    var newLatlng = new google.maps.LatLng(myJson.hotels[key].latitude,myJson.hotels[key].longitude);

    markers[key] =  new google.maps.Marker(
    {
      position: newLatlng,
      map: map,
      title: 'Hello World!'
    }); 
    // the code above works fine - it renders 4 pins o my map

    infowindows[key] = new google.maps.InfoWindow(
    {
     content: contentString
    });           

    google.maps.event.addListener(markers[key], 'click', function() {
      //console.log(key);  <-- this always return [3]
      infowindows[key].open(map,markers[key]);
    }); 

    //console.log(key); <-- this always return the right key - 0,1,2,3
  }    
}

Upvotes: 0

Views: 52

Answers (2)

Artur Stary
Artur Stary

Reputation: 744

I used a @phylax hint and I solved the problem this way:

I made a new function:

function addClickEventToMarker(aMap,aKey){
  google.maps.event.addListener(markers[aKey], 'click', function() {
      //console.log(key);  <-- this always return [3]
      infowindows[aKey].open(aMap,markers[aKey]);
  });
}

and I call the function in my 'for' loop:

for(key in myJson.hotels)
    {
    var newLatlng = new google.maps.LatLng(myJson.hotels[key].latitude,myJson.hotels[key].longitude);

    markers[key] =  new google.maps.Marker(
    {
      position: newLatlng,
      map: map,
      title: 'Hello World!'
    }); 


    infowindows[key] = new google.maps.InfoWindow(
    {
     content: contentString
    });           
    addClickEventToMarker(map, key);
  }    
}

Upvotes: 0

phylax
phylax

Reputation: 2086

The function in addListener gets called asynchronously. When it gets called you dont know which value key has.

You can come arround this by storing the key in a closure.

google.maps.event.addListener(markers[key], 'click',
  function (k) {
    return function() { infowindows[k].open(map,markers[k]);
  }(key)
}); 

Upvotes: 1

Related Questions