More advanced stuff

Google Maps API Tutorial

Context Menu

You may have noticed that maps.google.com now has a context menu that can be invoked with a right click.

It is possible to create context menus for your own API maps by using the “singlerightclick” event.

Here’s an Example

There’s nothing in the API to help you construct the context menu itself. You have to write your own code to do that.

What I basically do in that example, is to create a hidden div that contains the menus and has onclicks that each call a global function. When the user right-clicks the map, the “singlerightclick” event is triggered, and it returns a GPoint() indicating the pixel position of the click relative to the map container.

When the code detects such an event, I:

  • Store a copy of the pixel position in a global variable, in case any of my global functions need it later.
  • Check if the position is close to the right or bottom edge and adjust the context menu position accordingly.
  • Create a GControlPosition() for the position of the context menu.
  • Apply() the GControlPosition to the context menu div.
  • Make the context menu visible

Whenever there’s a click on one of the menu options, I perform the requested event, and then close the context menu.

Whenever there’s a click on the map or one of its clickable overlays, I close the context menu.

If one of the functions needs to know where on the map the right-click occurred, I read the pixel location from the global variable and convert it to a GLatLng with map.fromContainerPixelToLatLng().

The strange looking divs inside the links are there to make the whole width of the menu clickable.
Without them, only the actual text would be clickable.

You can obviously get your context menus to contain whatever options you want. You could even generate the .innerHTML of the context div dynamically when the right click occurs, with different options depending on the context.

Bits I’ve not figured out yet

  • The maps.google.com context menus close when the mouse exits the map container outwards, but not when it exits the map container by hovering over the context menu.
Advertisements