views:

648

answers:

4

The follwoing code loops over a json object to place marker on a google map. Which works fine.

function displayMarkers(data){
    for(var i = 0; i < data.Lat.length; i++){
     var point = new GLatLng(data.Lat[i],data.Lng[i]);
     marker = new GMarker(point);
     map.addOverlay(marker);

            // here's the problem
     GEvent.addListener(marker, "click", function(){
      alert(data.Name[i]);
     });
    }
}

The problem is, every marker always responds with the last value of "i". I'm stuck trying to figure out a way to identify the marker that has been clicked to somehow get the right information from the data object.

I'm thinking about creating an array of markers at creation to loop through based on the markers location, but that feels really inefficient to me.

Any help, as always, greatly appreciated.

A: 

Simple as pie.

    GEvent.addListener(marker, "click", function(o){
            alert(o);
    });
Oli
+3  A: 

The click event for the map passes three different elements.

GEvent.addListener(map, "click", function(overlay, latlng, overlaylatlng) {
  // overlay = GOverlay or null
  // latlng = GLatLng
  // overlaylatlng = GLatLng or null
});

If the user did not click on an overlay, 'overlay' and 'overlaylatlng' will be null.

Update: You have to add the listener to the map (not the marker) if you want to get a GOverlay out of it. The click event for a GMarker only returns the GLatLng.

Chris B
A: 
gargantaun
Ah, you are totally right. The problem is that we're adding the listener to the marker, not to the map. If you add the listener to the map, it will work as expected - and you only have to add the listener once.
Chris B
Cool, thanks for that.
gargantaun
+1  A: 

The Map supports an onTap event, which passes the index of the marker which was selected, please refer to this example:

Jaco