Skip to: Site menu | Main content

Email LinkedIn

Blog...

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:

Setup jQuery and Google Maps libraries:

<script type="text/javascript" src="/lib/jquery/jquery.js"></script>

<script src="http://maps.google.com/maps?file=api&v=2&key={Your Google Maps API Key}" type="text/javascript"></script>

Style the map <div>


<style>
#map {
border:1px solid #000000;
height:500px;
width:500px;
}
</style>

Use the handy jQuery $(document).ready() method:


<script type="text/javascript">
//<![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>

Google documents recommend unloading the widget:


$(document.body).unload(function() {
if (GBrowserIsCompatible()) {
GUnload();
}
});
Launch Demo 1 | View Javascript

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

Inside our $(document).ready() block:

$.ajax({type:"GET",url:"/demos/Google-Maps-the-jQuery-Way/markers.xml",dataType:"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.");
}});
Launch Demo 2 | View Javascript | View XML

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:

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
jQuery has a maps plugin, but I wanted to demonstrate using jQuery with an external library.

http://jquery.com/plugins/project/jmaps
# Posted By Jason Holden | 11/21/07 2:51 PM
Excellent post. It's definitely nice to be able to detect the onload jQuery style. As far as the jQuery plugin - in most cases, I think it's quite nice to use pure jQuery to gets things done, but I think that the Google Maps API is sufficiently simple in this case. In any case, I think that plugin needs some work before it sees very extensive use.
# Posted By Evan | 8/6/08 12:39 AM
any reason you are doing this:
document.getElementById("map")

instead of this:
$('map')
# Posted By Mike Causer | 4/4/09 10:57 AM
@Mike

The GoogleMap API would not accept a jQuery object.

This may have been a jQuery issue or a GoogleMap issue. Not sure. I haven't attempted it with the updated versions.
# Posted By Jason Holden | 4/4/09 3:59 PM
GoogleMap cannot use jQuery wrapped set; instead, it requires a javascript element and doing that is easy in jQuery as follows:
$('map').get(0)
or
$('map')[0]
# Posted By Imran Rashid | 4/6/09 1:05 AM
I have been working on a jQuery plugin that might be helpful to others reading this blog.

It allows you to easily get a google-map on your site, manage markers, custom icons, sidebars.... ect.

http://www.blocsoft.com/bmap/

Darren
# Posted By Darren | 4/7/10 12:41 AM