Grumpy
Grumpy

Reputation: 2253

google maps multiple markers clickevent

Im looping and placing some markers, but when i click a marker, they all respond with the same value

Here is my code

  for(a=0; a < prod.length; a++){      
  // we add marker to map  
  var myLatlng = new google.maps.LatLng(prod[a]['lat'],prod[a]['lon']);
  var marker = new google.maps.Marker({
  position: myLatlng,
  map: map,
  title: prod[a]['name']+" \n"+prod[a]['description'],
  icon: image
  });        
  google.maps.event.addListener(marker, "click", function() {
    show_details(a);
  });      
}

function show_details, a always has the same value

I have looked at the other answers here but that didnt solve my problem.

Upvotes: 2

Views: 5274

Answers (1)

Kovge
Kovge

Reputation: 2019

Tipical problem in async programming/scripting. The a variable passing, when the click event runs, so , the value of that is what is after the for loop finishes. You should create an inner function scope, and save the value of a in a variable, what lives only in that scope. The solution:

 (function(z){
    google.maps.event.addListener(marker, "click", function() {
       show_details(z);
    });    
 })(a);

The a variable lives outside the callback function too. So if you modify the value of a ( or the for loop modify that) and when the event handler is called, it see the modified a.

Help link: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/ .

Upvotes: 10

Related Questions