How to dynamically serve a KML file in 2.0

KML is the markup language that Google uses to represent markers in Google Earth – and NOW in Google Maps!

How it works, is that you store the KML in a file on a web server where Google can get at it. Google then goes at caches the file, and generates the output map markers.

But what if you want to display dynamic markers using KML?

Here’s how:

First add an aspx page to your project. This will be the page to serve the KML.

Create an xml document that will represent the kml file using the XmlDocument class. Should look something like this:

XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0","utf-8",null); 
// Create the root element
XmlElement rootNode  = xmlDoc.CreateElement("kml");
rootNode.SetAttribute("xmlns", @"");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement); 
XmlElement documentNode = xmlDoc.CreateElement("Document");
XmlElement iconNode = xmlDoc.CreateElement("Icon");
XmlElement iconHrefNode = xmlDoc.CreateElement("Href");
XmlText iconHrefText = xmlDoc.CreateTextNode("marker_image.gif");
// MyMarkerClass is my own object used to hold my internal longlat stuff - replace with your own mechanism here
foreach (MyMarkerClass marker in markers)
 // Create a new  element and add it to the root node
  XmlElement placeMarkNode = xmlDoc.CreateElement("Placemark");
  // Create the required nodes
  XmlElement nameNode = xmlDoc.CreateElement("name");
  XmlText nameText = xmlDoc.CreateTextNode(marker.Name);
  XmlElement descNode = xmlDoc.CreateElement("description");                
  XmlText descriptionText = xmlDoc.CreateTextNode(marker.Description);                
  XmlElement pointNode = xmlDoc.CreateElement("Point");
  XmlElement coordsNode = xmlDoc.CreateElement("coordinates");
  XmlText coordsText = xmlDoc.CreateTextNode(string.Format("{0},{1},{2}", marker.Long, marker.Lat, 0));

Then, in your Page_Load method, write theKMLdirectly to the output like this:

Response.ContentType = "application/x-msdownload";
XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, null);

Almost there! Now you’ll need to rewrite the url so that Google can try and find it with an innocuous “myfile.kml” path. We created a url rewriting method in house, but there are tutorials on line on how to do it (try here or here )

Now all you need to do is include the url rewritten kml path in your javascript, and Google will use it beautifully!

Subscribe via RSS

Back to all blog posts