27.10.2014 Views

Google Maps API 3

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 7 ■ INFOWINDOW TIPS AND TRICKS<br />

// First we create the container for the content<br />

// of the InfoWindow<br />

var content = document.createElement('div');<br />

// We then create a paragraph element that will contain<br />

// some text<br />

var p = document.createElement('p');<br />

p.innerHTML = 'This marker is positioned on Manhattan.';<br />

// We then create a second paragraph element that will contain<br />

// the clickable link<br />

var p2 = document.createElement('p');<br />

Now you need to create the link. You start by creating a element and give it a text and a value to<br />

its href attribute.<br />

// Creating the clickable link<br />

var a = document.createElement('a');<br />

a.innerHTML = 'Zoom in';<br />

a.href = '#';<br />

■ Note The standard way of assigning values to HTML elements is the DOM method setAttribute(). But since<br />

there are some differences in implementation in different browsers (mainly IE), I stick with the attributes<br />

innerHTML and href since they are supported by all browsers. Another approach could be to use a JavaScript<br />

framework such as jQuery or prototype to do this. They will take care of the browser inconsistencies for you.<br />

OK, so now that the element is created, it’s time to add the magic that will zoom the map. You<br />

will do this by assigning an anonymous function to its onclick event. In the anonymous function, you<br />

will add the code that will do the heavy work in this example.<br />

a.onclick = function() {<br />

// Code goes here<br />

}<br />

You probably recognize this syntax since it’s the same as the one you’ve been using all along when<br />

attaching an onload event to the windows object.<br />

■ Note There are other ways of attaching click events to an element than using the onclick property. The benefit<br />

of using onlick is that it’s cross-browser compatible. The standard way of doing it, using the method<br />

addEventListener(), involves having to provide a separate method for IE called attachEvent() since it doesn’t<br />

support it.<br />

152

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!