Wednesday, February 9, 2011

JSON in KML Templates

Since Google Earth 5.0, the description balloon has handled pretty close to full JavaScript. There's some interesting things you can do with this. In this example, I'm showing a very basic use of JSON using KML balloon templates.

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
    <Style id="testStyle">
      <BalloonStyle>
        <text><![CDATA[
          <script type="text/javascript">
             function loadData(){
               var foo = $[foo];
               var myObj = foo.myData[1].value;
               document.getElementById("example").innerHTML = myObj;
             }
           </script>
           <body onload="loadData()">
             <div id="example">test</div>
           </body>
          ]]>
        </text>
      </BalloonStyle>
    </Style>
    <Placemark>
      <styleUrl>#testStyle</styleUrl>
      <ExtendedData>
        <Data name="foo"><value>{"myData":[
          {"value":"1"},{"value":"50"}]
          }</value></Data>
        <Data name = "bar"><value>23094</value></Data>
      </ExtendedData>
      <Point>
        <coordinates>0,0</coordinates>
      </Point>
    </Placemark>
  </Document>
</kml>

Balloon templates are designed to allow you to use a single <Style> element for all or a set of your <Placemark;gt; elements, and then just insert <Feature> specific data into the template. Named <Data> elements inside a <ExtendedData> element provide name/value pairs. However, this can be a little flat. You can put JSON elements inside the <value> element (a child of <Data>, which gives you a lot more flexibility.

The good folks at Secorra provide ObsKML, an ocean observations format, using this technique.

No comments: