Google Maps the jQuery Way
I just recently had the opportunity to start working with jQuery. What an amazing library. It has changed the way I write Javascript. As one of my first experiments I used jQuery to integrate Google Maps into a project. jQuery makes it so easy to work with the DOM and browser events.
I've decided to provide a quick example of how to use jQuery and Google Maps.
I'm assuming you have already gotten your Google API key. If not, click here to get one for free.
First I need to do a little setup:
<script src="http://maps.google.com/maps?file=api&v=2&key={Your Google Maps API Key}" type="text/javascript"></script>
#map {
border:1px solid #000000;
height:500px;
width:500px;
}
</style>
//<![CDATA[
var map;
var markers = [];
$(document).ready(function() {
if (GBrowserIsCompatible()) {
// Initialize the map.
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.setCenter(new GLatLng(39.1,-94.595), 9);
}
});
//]]>
</script>
if (GBrowserIsCompatible()) {
GUnload();
}
});
In this example I simply used jQuery to ensure the document was ready to manipulate and to ensure the widget is unloaded. jQuery makes it easy to work with any browser event.
The map centers over Kansas City, MO. The .setCenter() method accepts a GLatLng class so you need the latitude/longitude to center. The second setCenter() parameter is the zoom level. Adjust this up or down to change the initial zoom level.
Next we need to add some push pins. This is where jQuery really shines. Server interaction and traversing structured data is so easy.
I'm going to pull my point data from an XML file markers.xml
success:function(data,textStatus) {
$("marker",data).each(function() {
// Attributes for each marker.
var lat = parseFloat($(this).attr("lat"));
var lng = parseFloat($(this).attr("lng"));
var point = new GLatLng(lat,lng);
var html = $("html",this).text();
// Create the marker.
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
});},
error:function(XMLHTTPRequest,textStatus,errorThrow){
alert("There was an error retrieving the marker information.");
}});
I created a jQuery AJAX request and setup an inline success and failure callback. Next, jQuery's $.each() method allows me to iterate the collection of markers. For each marker node in the XML data file a new GMarker class is created and added to the map. I've also updated the zoom level in the .setCenter() method.
Watch out for cached XML data. Both IE and Firefox have a tendancy to cache the XML file.
I hope I've demonstrated how jQuery can compliment other javascript libraries and widgets.
More Links:



http://jquery.com/plugins/project/jmaps