0

When I use google.maps.event.trigger on a google.maps.Data.Layer that is listening for click events, the latLng object is getting passed to my listener instead of the actual click on the feature:

//feat is generic google.maps.Data object
feat.addListener('click', function (e) {
        console.log(e);
    });

//  the event is the latLng object
//  place is the same location as when I manually click on the map
google.maps.event.trigger(feat, 'click', {
                    latLng: place.geometry.location
                });
>>> Object {latLng: L}

//  when I actually click at the same position, the event is different
>>> NW {latLng: L, Gb: MouseEvent, pixel: undefined, Ja: undefined, feature: Ec}

How can I manually trigger a click event that has the same form as actually clicking on the map?

camdenl
  • 1,159
  • 4
  • 21
  • 32

1 Answers1

1

The problem is this: The callback function on the click event on the Data class has a Data.MouseEvent available to it:

https://developers.google.com/maps/documentation/javascript/reference#Data.MouseEvent

i.e. in this code, e is a Data.MouseEvent:

feat.addListener('click', function (e) {
    console.log(e);
});

So when you output e to the console, that's what you're seeing when you get:

NW {latLng: L, Gb: MouseEvent, pixel: undefined, Ja: undefined, feature: Ec}

But the only value you're passing to the event when you trigger it is a LatLng object. If you want to make it the same, you'd need to construct a Data.MouseEvent instead.

Something like this I think:

var event = new google.maps.Data.MouseEvent({
   latLng: place.geometry.location 
});

google.maps.event.trigger(feat, 'click', event);

You'd maybe also need to specify the feature property for that Data.MouseEvent; I'm not sure if you'd just be able to use the Data object you've already got:

var event = new google.maps.Data.MouseEvent({
   latLng: place.geometry.location,
   feature: feat 
});
duncan
  • 31,401
  • 13
  • 78
  • 99
  • Says google.maps.Data.MouseEvent is not a function, is that working for you? – camdenl Oct 23 '15 at 18:43
  • @camdenl hmmm, try `new google.maps.MouseEvent({latLng: place.geometry.location})` instead perhaps? – duncan Oct 23 '15 at 18:47
  • Still not a function, I don't think the library provides a way to construct those objects, which might be the problem I'm facing. – camdenl Oct 23 '15 at 18:49
  • you could try this approach, where the `stop` function is specified too: http://stackoverflow.com/a/12438154/492335 – duncan Oct 23 '15 at 18:54
  • Please note there is no need of Data.MouseEvent. Infact you can't create new google.maps.Data.MouseEvent (this would be undefined according to new gmap API). As long as you create normal event object and pass the feature object with right lat and long it should work. – connect2Coder Jan 04 '21 at 21:21