I tried searching on Google Maps API documentation and also here but I couldn't find out how to do this.
I am trying to set the arrow keys navigation by default on my Map, without the needing to click on the Map area in order to enable that.
I tried the following solution without success:
map.getDiv().focus();
document.getElementById("map_canvas").focus();
google.maps.event.trigger(map, 'rightclick');
Anyone have a clue how that can be done?
Thank you all.
Couple of things to take note of here, simply using .focus()
or triggering a click action on the #map
div element will not do the trick because those actions take place before the map actually gets rendered on the DOM. So, the first thing to acknowledge is the use of the tilesloaded
event the google maps library provides.
google.maps.event.addListener(map, 'tilesloaded', function() {
//do actions
});
The second thing I came to find out is you can't just add $('#map').click()
inside the event listener. This is because though the #map
is the container div - the google maps script actually renders a whole bunch of other divs on top of it (which have higher z-indices and are also what actually holds your map tiles). With a little bit of hacking around, and jquery you can narrow down to the div that contains the tiles and trigger the click event on that div...resulting code was:
google.maps.event.addListener(map, 'tilesloaded', function() {
$("#map").children().children().first().children().trigger('click');
});
I used Chrome's Dev tools to narrow down to the div containing the tiles and used jquery's children()
method to traverse to that div from the #map
. If you stick that code into your init function, you should be good to go. Here's a JSfiddle with a working example of the solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With