Thursday, July 9, 2009

Creating custom controls in Google Maps

If you haven’t played around with Google Maps or had a look at the API yet, then it’s about time and you’re in for a treat! The joy of working with Google Maps is partly due to the impressive documentation, but most of all it’s due to the fact that a lot can be achieved in just a couple lines of code.

We’ve all seen the standard version of Google Maps:


The code for this is extremely simple:



In the first script tag the Google Maps API javascript is registered. A div tag is included wherever the map should be displayed on the page, and a second script tag containing a call to the init() function is added below the div.

The init() function itself retrieves the

element, creates a map and sets the center. SetUIToDefault() adds a zoom control to the left and the map type buttons in the right upper corner.

So far so good, but what if we want a custom button instead the of map type buttons as in the map below?



The init() method itself does not change much. Remove setUIToDefault()and add two controls, one zoom control (GLargeMapControl3D) and one custom control.



In order to create the custom control, the function must be defined and the custom control must subclass GControl. The initialize function creates a

within the map and defines a DomListener for the click event. At last, the buttonDiv is returned in order for the correct position to be set:



In this example, nothing actually happens when clicking the button as I left the click event empty. There are however a lot of interesting things one can do. One example is from the project I’m currently working on where all blog posts are geotagged with a location and is displayed with a marker on the map after clicking the button.

Try it out!

4 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. thanks. very simple process...

    ReplyDelete
  3. I'm trying to add rotation for Google Maps API version 2 for a custom map. It's only supported on oblique at certain zoom level such as hybrid maps. Does anyone know how to do custom rotations?

    ReplyDelete
  4. Wow. Not that useful. You just ripped the code out of the documentation and slapped it up here almost verbatim.

    ReplyDelete