Is there a way to determine which Google Map Marker was clicked?

The following code iterates over a json object to place a marker on a google map. Which works great.

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 the problem GEvent.addListener(marker, "click", function(){ alert(data.Name[i]); }); } } 

The problem is that each marker always answers with the last value of "i". I was stuck trying to figure out a way to identify a marker that was pressed in order to somehow get the right information from a data object.

I'm thinking of creating an array of markers when creating a loop based on the location of the markers, but for me it is really inefficient.

Any help, as always, is greatly appreciated.

+4
source share
4 answers

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 the overlay, "overlay" and "overlaylatlng" will be empty.

Update:. You must add a listener to the map (and not to the marker) if you want to get GOverlay. The click event for GMarker returns GLatLng.

+4
source

The map supports the onTap event, which passes the pointer of the marker that was selected, see this example :

+1
source

It seems that the above solutions only return marker coordinates, which does not solve my problem. Maybe I'm doing something wrong.

However, as I decided, it’s just adding a property to a marker like this

 function createMarker(latlng,name) { var marker = new GMarker(latlng); // HERE WE GO marker.value = name; GEvent.addListener(marker,"click", function() { addToList(this.value); }); return marker; } 

Strike> UPDATE: The aboves solves it one way, but the easiest way is to attach an event to a map, as indicated in the comments

 GEvent.addListener(map, "click", function(marker, point){ alert(marker); }); 
0
source

Just like a pie.

  GEvent.addListener(marker, "click", function(o){ alert(o); }); 
-2
source

All Articles