How to "simulate" a click on a Google Maps Marker?
Asked Answered
T

2

16

What I'd like to do is to invoke the click handler on a marker. So this is my code :

var marker = new google.maps.Marker({
    position: location,
    map: map,
    title: title
});    

google.maps.event.addListener(marker, 'click', function() {
    alert("clicked");
});        

marker.click();

but I cannot see any alert...

Teaspoon answered 8/2, 2012 at 13:49 Comment(2)
Check here: code.google.com/apis/maps/documentation/javascript/…Wellmeaning
Already read, but it doesnt explain my request :OTeaspoon
B
33

It's possible to trigger any Maps API event listener on any object using the google.maps.event.trigger function.

You'll probably want to pass in a mock MouseEvent object, depending on what your event listener(s) do with it.

Example:

google.maps.event.trigger(marker, 'click', {
  latLng: new google.maps.LatLng(0, 0)
});
Bowra answered 8/2, 2012 at 14:13 Comment(5)
Can you give to me an example?Teaspoon
This doesnt reply to my answer actually :OTeaspoon
Yes, which is exactly what I gave you. I don't understand what you don't understand. Add the code in my answer to the end of your sample code, and you should see an alert pop up.Bowra
No, it doesn't. It only triggers it on the Marker you pass in as the first argument.Bowra
This solution does not work in clustered markers (one of the group markers) situation. Please share suggestion if you have. Thanks.Tatum
B
7

Save your markers in an array. And do something like this:

$('#anotherButton').click(function(){
   google.maps.event.trigger(marker[index], 'click');
});
Base answered 9/12, 2013 at 14:52 Comment(1)
This solution does not work in clustered markers (one of the group markers) situation. Please share suggestion if you have. Thanks.Tatum

© 2022 - 2024 — McMap. All rights reserved.