Google Maps API Tutorial© 2006, 2007,2008, 2009 Mike Williams |
Translate this page: |
SidebarOn the actual Google maps page there's a panel on the left where you can click on a link to pop the info window open on a specific marker.How do we do that with the API? Here's a simple example Link to the example and view the source. The method involves setting up an empty <div> which is going to contain the clickable list, collecting the clickable html for each marker at the same time as we create each marker, then finally placing the assembled chunk of html into the <div>. This time, it's not possible to use function closures to hold all the variables we're going to need later, at the time when the sidebar entry gets clicked, so we build an array of markers, which we use to specify which marker should get the info window. I use the createMarker() function to handle all this. It creates the marker, sets up the listener for the marker "click" event, inserts entries into the gmarkers[] array, and adds an entry to the sidebar list. The "gmarkers.length" information isn't preserved by function closure, it gets turned into text and written into the html. This line side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '</a><br>';creates a string of html like this <a href="javasript:myclick(1)">That Place</a><br> The myclick(i) function triggers a "click" event on the marker, and the info window opens just as it would if the user clicked the marker. After all the markers have been created, the assembled sidebar html code is put into document.getElementById("side_bar").innerHTML Potential Pitfalls
Here's an example that uses lettered markers. Potential Pitfalls
Here's an example that puts the sidebar into a custom GControl. Here's an example that highlights the corresponding entry in the sidebar whenever the info window is open. Note that the "linkid" variable, which identifies the link being highligthed, must be local to the createMarker() function, so that it holds function closure, and the "lastlinkid" variable, which remembers which link needs to be set back to the default style, must be global.
You can use any style change you like to highlight the sidebar entry. In this case I turn the background yellow. |