Archive for June, 2009

jQuery and Google Maps with KML

Marc Grabanski has written a great tutorial on how to spice up Google Maps using JQuery. What I have done is a slight variation of his tutorial.

Instead of placing ten random markers on the map, we will generate driving directions from point A to B and use the KML data from Google Maps to render the markers.
Appending “&output=kml”, Google Maps will return a KML document which we can then parse to get the marker information.

var geoXml;
var urlKML = "http://maps.google.com/maps?saddr=";
urlKML += fromAddress.val();
urlKML += "&daddr=";
urlKML += toAddress.val();
urlKML += "&output=kml";
geoXml = new GGeoXml(urlKML);

We can now create an XMLDOM object using the KML and parse the nodes to get all the marker coordinates and its description.

var doc = new ActiveXObject("Microsoft.XMLDOM");
doc.async = false;
doc.load(urlKML);
if (doc.parseError.errorCode != '0') {
errordiv.innerHTML = "Error generating KML! Probably an invalid address...";
return false;
} else errordiv.innerHTML = "";
var coords = doc.documentElement.selectNodes("Document/Placemark/Point/coordinates");
var places = doc.documentElement.selectNodes("Document/Placemark/name");

We can now loop through each and add the markers to the map.

for (var i = 0; i < coords.length; i++) {
var pts = [];
pts = coords[i].text.replace(",0", "").split(",");
var point = new GLatLng(pts[1], pts[0]);
marker = new GMarker(point);
map.addOverlay(marker);
markers[i] = marker;
}

And append the description to each marker using the .html property:

$(markers).each(function(i, marker) {
$("<li />")
.html(places[i].text)
.click(function() {
displayPoint(marker, i);
});
GEvent.addListener(marker, "click", function() {
displayPoint(marker, i);
$("#myInfoWindow")
.html(places[i].text)
});
});

You can view the final demo here.
Its still work-in-progress so feel free to chime in with your suggestions. Next I am going to add to the map are lines connecting the markers with each other.