Simulate a click in a Google Map
Asked Answered
Z

1

15

I'm trying to simulate a user click on a Google Map, using API v3, after I geolocate their position when they write down their address.

I used to do:

google.maps.event.trigger(map, 'click', {
    latLng: new google.maps.LatLng(lat, lng)
});

But now I got an error:

Uncaught TypeError: Cannot read property 'wa' of undefined main.js:727

I need to simulate the click because I'm using Drupal with a CCK field, and it's doing this on clicks under the hood that are not triggered if I add the location pick as a marker.

Zilvia answered 14/9, 2012 at 12:7 Comment(3)
What are the values of lat and lng? Are you trying to get the current lat lng of the click? The click needs to be on the map to bubble the event which would contain the lat lng...if that's what you're trying to get? I guess we need to see more code to figure out what the solution might be.Negro
No, I want to force a click on the element, sending the lat & long to it.Zilvia
Would that element be embedded into the google map? I mean if you put a marker on the map, give it an id, you can access that marker.?Negro
D
24

The map object's 'click' event takes a google.maps.MouseEvent object as parameter:

var mev = {
  stop: null,
  latLng: new google.maps.LatLng(40.0,-90.0)
}

google.maps.event.trigger(map, 'click', mev);

Live example here

Danged answered 15/9, 2012 at 14:21 Comment(8)
I got an "Uncaught TypeError: Cannot call method 'trigger' of undefined". It seems that google.maps.event is not defined. If I try with google.maps.Event I get the same error: "Uncaught TypeError: Cannot read property 'wa' of undefined main.js:727"Zilvia
I've tested it and it works fine. You must have some other error.Danged
If google.maps.event is not defined, you are trying to use the Google Maps API before it is loaded or without loading it.Centurial
I've changed the including of the API to the following url: "maps.google.com/maps?file=api&v=3.9&key=MyKey&hl=es". GMaps is initialized correctly, when I'm triggering this event the DOM is fully loaded... Now I don't see any js error in the console, but any marker appears.Zilvia
btw, looks like the culprit is that the drupal gmaps module doesn't support v3 throught my hacks for including the 3.8 API: drupal.org/node/818638Zilvia
Giving the bounty to @Danged for his support :-), but now I need to change my approach completely :/Zilvia
Thanks! ... and BTW you can see the simulated click in action here: maps.forum.nu/v3/gm_elevation.htmlDanged
Finally solved it with API v2, thanks for your support: GEvent.trigger(map, 'click', null, new GLatLng(lat, lng, true), null);Zilvia

© 2022 - 2024 — McMap. All rights reserved.