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 10 ■ LOCATION, LOCATION, LOCATION<br />

}<br />

})();<br />

geocoder.geocode(geocoderRequest, function(results, status) {<br />

// Check if status is OK before proceeding<br />

if (status == google.maps.GeocoderStatus.OK) {<br />

}<br />

});<br />

// Center the map on the returned location<br />

map.setCenter(results[0].geometry.location);<br />

// Check to see if we've already got a Marker object<br />

if (!marker) {<br />

// Creating a new marker and adding it to the map<br />

marker = new google.maps.Marker({<br />

map: map<br />

});<br />

}<br />

// Setting the position of the marker to the returned location<br />

marker.setPosition(results[0].geometry.location);<br />

// Check to see if we've already got an InfoWindow object<br />

if (!infowindow) {<br />

// Creating a new InfoWindow<br />

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

}<br />

// Creating the content of the InfoWindow to the address<br />

// and the returned position<br />

var content = '' + results[0].formatted_address + '';<br />

content += 'Lat: ' + results[0].geometry.location.lat() + '';<br />

content += 'Lng: ' + results[0].geometry.location.lng();<br />

// Adding the content to the InfoWindow<br />

infowindow.setContent(content);<br />

// Opening the InfoWindow<br />

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

Extending the Example<br />

You can do several things to improve this example. First, you should include better error handling so<br />

when something goes wrong, you can let the user know what happened. Second, you could take care of<br />

all the results instead of just the first one in the results array. This is done by looping through the<br />

results array and adding each location as a marker to the map.<br />

222

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

Saved successfully!

Ooh no, something went wrong!