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 5 ■ X MARKS THE SPOT<br />

What happens here is that instead of creating a new InfoWindow every time the user clicks a<br />

marker, you just move the existing one around and at the same time change its content. It’s easy to<br />

check whether the variable infowindow is carrying an object with an if statement. An empty variable<br />

will return undefined, which means false in JavaScript. If it, on the other hand, carries an object, it will<br />

return the object, which in JavaScript is the same thing as true.<br />

Before, you defined the content of the InfoWindow upon its creation. Since you now reuse the same<br />

InfoWindow object over and over again, you need to set the content in some other way. Fortunately, the<br />

InfoWindow object has a method called setContent() that will do exactly that. This method takes plain<br />

text, HTML, or a reference to an HTML node as its value, much like the content property of the<br />

InfoWindowOptions object did. You’re going to give it the exact same value as you gave the content<br />

property early.<br />

With that in place, all you need to do is to open the InfoWindow (Listing 5-19).<br />

Listing 5-19. Finalizing the Event Handler<br />

// Add click event to the marker<br />

google.maps.event.addListener(marker, 'click', function() {<br />

// Check to see if the infowindow already exists and is not null<br />

if (!infowindow) {<br />

// if the infowindow doesn't exist, create an<br />

// empty InfoWindow object<br />

infowindow = new google.maps.InfoWindow();<br />

}<br />

// Setting the content of the InfoWindow<br />

infowindow.setContent('Place number ' + i);<br />

// Tying the InfoWindow to the marker<br />

infowindow.open(map, marker);<br />

});<br />

Now the code will produce a map that will display only one InfoWindow at a time. Listing 5-20<br />

shows the complete code.<br />

Listing 5-20. The Complete Code for Example 5-4<br />

(function() {<br />

window.onload = function() {<br />

// Creating an object literal containing the properties<br />

// you want to pass to the map<br />

var options = {<br />

zoom:3,<br />

center: new google.maps.LatLng(37.09, -95.71),<br />

mapTypeId: google.maps.MapTypeId.ROADMAP<br />

};<br />

// Creating the map<br />

var map = new google.maps.Map(document.getElementById('map'), options);<br />

// Creating an array which will contain the coordinates<br />

94

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

Saved successfully!

Ooh no, something went wrong!