Search This Blog

Tuesday, October 26, 2010

KML in Google Maps API

There are various ways of loading layers over google maps. One way is creating spatial objects and loading it from within the Java Script. If you you do not wish to touch the Java script code an alternative is using KML (Keyhole Markup language) file. Its basically in XML format and some things need to be taken into consideration when writing one, as a single silly mistake can get on your nerves. In this example i have drawn a polygon across a small area. Below is what you will have in your html :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps KML</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA"
            type="text/javascript"></script>
    <script type="text/javascript">
    function initialize() {
      if (GBrowserIsCompatible()) {
 var msg = document.getElementById("message");
        var map = new GMap2(document.getElementById("map_canvas"));
 var gx = new GGeoXml("http://testing.codeconnect.in/polygon5.kml");
 map.setCenter(new GLatLng(15.589200424519804, 73.81010591983795), 17);
 map.addControl(new GLargeMapControl());
        map.addOverlay(gx);
        
      }
    }  
    </script>
  </head>

  <body onload="initialize()" onunload="GUnload()">
    <div id="map_canvas" style="width: 500px; height: 300px"></div>
    <div id="message"></div>
  </body>
</html>
Object gx holds this KML file . You just have to add it as an overlay. Remember, your kml files have to on some public server and not localhost. The content of KML is as follows :

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">

<Document>
<name>polygon4.kml</name>

<Placemark>
<name>Test</name>
<Polygon>
<altitudeMode>relativeToGround</altitudeMode>
 <outerBoundaryIs>
  <LinearRing>
   <coordinates>
    73.809323,15.589077,0 
    73.809913,15.589873,0
    73.809913,15.589873,0
    73.809902,15.589858,0
    73.810229,15.589692,0
    73.810503,15.589,0
    73.810202,15.58869,0 
    73.809323,15.589077,0
   </coordinates>
  </LinearRing>
 </outerBoundaryIs>
</Polygon>
</Placemark>
</Document>

</kml>
In The KML file, the first thing that should be taken care of is namespace or xmlns="http://www.opengis.net/kml/2.2" which, if is wrong, Google won't load that kml. Each object can be displayed using Placemark which has a name and the object definition (Polygon in my case). Additionally you can add markers, polyline etc.

No comments:

Post a Comment