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.
<br />var geoXml;<br />var urlKML = "http://maps.google.com/maps?saddr=";<br />urlKML += fromAddress.val();<br />urlKML += "&amp;amp;amp;daddr=";<br />urlKML += toAddress.val();<br />urlKML += "&amp;amp;amp;output=kml";<br />geoXml = new GGeoXml(urlKML);<br />
We can now create an XMLDOM object using the KML and parse the nodes to get all the marker coordinates and its description.
<br />var doc = new ActiveXObject("Microsoft.XMLDOM");<br />doc.async = false;<br />doc.load(urlKML);<br />if (doc.parseError.errorCode != '0') {<br />errordiv.innerHTML = "Error generating KML! Probably an invalid address...";<br />return false;<br />} else errordiv.innerHTML = "";<br />var coords = doc.documentElement.selectNodes("Document/Placemark/Point/coordinates");<br />var places = doc.documentElement.selectNodes("Document/Placemark/name");<br />
We can now loop through each and add the markers to the map.
<br />for (var i = 0; i < coords.length; i++) {<br />var pts = [];<br />pts = coords[i].text.replace(",0", "").split(",");<br />var point = new GLatLng(pts[1], pts[0]);<br />marker = new GMarker(point);<br />map.addOverlay(marker);<br />markers[i] = marker;<br />}<br />
And append the description to each marker using the .html property:
<br />$(markers).each(function(i, marker) {<br />$("<li />")<br />.html(places[i].text)<br />.click(function() {<br />displayPoint(marker, i);<br />});<br />GEvent.addListener(marker, "click", function() {<br />displayPoint(marker, i);<br />$("#myInfoWindow")<br />.html(places[i].text)<br />});<br />});<br />
You can view download 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.
Comments(9)

