Google Maps API onClick listener example

Click on the map, go to a link - pretty easy. 
Today I wanted to share a quick example. You want a specific function to happen when someone clicks on your map. We're not talking about click on a marker to open a info window. Today I'm assuming you want to redirect someone to another page when they click anywhere on the map. 

To do this we create a DOM (Document Object Model) event listener, it's really easy and will take 40 seconds to explain. First we'll load a Google Map, and add a few lines of code.

Here is the code that makes it all happen:
<script type="text/javascript" 
      src="http://maps.google.com/maps/api/js?sensor=false"></script>

</head>

<body style="font-family: Arial; border: 0 none;">
   <div id="map-canvas" style="width: 500px; height: 400px"></div>
</body>

How's it work

You can see the map object is created by the function initialize. This is called when the addDomListener event 'load' is completed on line 17. On line 18 I add a new event for 'click'. I then put an inline function of giving a new value to window.location to make the page redirect. Replacing the site on line 17 with your site and you are good to go.

More information:

Popular posts from this blog

Connect to Gmail with Apps Script

How to create a Chrome Extension

Apps Script on tablets