Google Maps API using .kml files from "My Maps"


/ Published in: JavaScript
Save to your folder(s)

Sample script to use Google API to display a map with multiple marker layers that can be toggled on/off using checkboxes. The map data is provided using the .kml files provided from "My Maps" on Google, or Google Earth files.


Copy this code and paste it in your HTML
  1. <div id="map"></div>
  2.  
  3. <div id="controls">
  4. <p class="legend"><strong>Toggle a Checkbox to Show Map Points</strong></p>
  5. <ul>
  6. <li><input type="checkbox" id="layer1" onClick="boxclick(this, layer1);"/><label> Layer 1 </label></li>
  7.  
  8. <li><input type="checkbox" id="layer2" onClick="boxclick(this, layer2);"/><label> Layer 2 </label></li>
  9.  
  10. <li><input type="checkbox" id="layer3" onClick="boxclick(this, layer3);"/><label> Layer 3</a></label></li>
  11. </ul>
  12. </div>
  13.  
  14. <script type="text/javascript">
  15.  
  16. $(document).ready(function() {
  17. $('#controls input:checkbox').removeAttr ('checked');
  18. });
  19.  
  20.  
  21. if (GBrowserIsCompatible()) {
  22. var map = new GMap2(document.getElementById("map"));
  23. map.setCenter(new GLatLng(35.300855, -82.471115), 12);
  24. map.addControl(new GSmallMapControl());
  25. map.addControl(new GMapTypeControl());
  26. map.setMapType(G_PHYSICAL_MAP);
  27. map.addMapType(G_PHYSICAL_MAP);
  28.  
  29. // Google kml files stored on server: http://mydomain.com/google/filename.kml
  30. var layer0 = new GGeoXml("http://mydomain.com/google/layer0.kml"); //Default onload layer
  31. var layer1 = new GGeoXml("http://mydomain.com/google/layer1.kml");
  32. var layer2 = new GGeoXml("http://mydomain.com/google/layer2.kml");
  33. var layer3 = new GGeoXml("http://mydomain.com/google/layer3.kml");
  34.  
  35. // Show the defualt onload layer
  36. map.addOverlay(layer0);
  37. }
  38.  
  39. //Toggle layers on/off using checkboxes
  40. function boxclick(box,category) {
  41. if (box.checked) {
  42. map.addOverlay(category);
  43. } else {
  44. map.removeOverlay(category);
  45. }
  46. }
  47.  
  48. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.