Search code examples
htmlkmlgoogle-earth-plugin

Loading KML into Google earth?


I can't figure out why for example I try to reproduce something basic like this example https://google-developers.appspot.com/earth/documentation/samples/fetchkml_example on my own, I can't get it to work. I'm using my key that I have been using for my Google Maps API, so I think that part should be fine, but when it comes to KML I can't seem to get it to work regardless of whether it is fetched or parsed. I have put my KML file here https://sites.google.com/site/shahinkmlexamples/experiment/kml_example.kml , and my code is below with my own key number not shown

<html>
<head>
   <title>fetchkml_dom_example.html</title>
   <script src="//www.google.com/jsapi?key=MYKEY#"></script>
   <script type="text/javascript">
      var ge;
      google.load("earth", "1");

      function init() {
         google.earth.createInstance('map3d', initCB, failureCB);
      }

      function initCB(instance) {
         ge = instance;
         ge.getWindow().setVisibility(true);

         var href = 'https://sites.google.com/' + 'site/shahinkmlexamples/experiment/kml_example.kml';

         google.earth.fetchKml(ge, href, function(kmlObject) {
               if (kmlObject)
                  ge.getFeatures().appendChild(kmlObject);
               if (kmlObject.getAbstractView() !== null)
                  ge.getView().setAbstractView(kmlObject.getAbstractView());
         });
      }

      function failureCB(errorCode) {
      }

      google.setOnLoadCallback(init);
   </script>

</head>
<body>

   <div id="map3d" style="border: 1px solid silver; height: 400px; width: 600px;"></div>

</body>
</html>

so I know the solution has got to be simple, but I just can't figure it out. Thanks


Solution

  • When you're loading it from a local file (such as using notepad++ and loading that file in Chrome) you need to add a protocol to the script tag:

    <script src="//www.google.com/jsapi?key=MYKEY#"></script>
    

    Becomes:

    <script src="https://www.google.com/jsapi?key=MYKEY#"></script>
    

    Without that change, your page is looking for the file in your local filesystem.

    It's left out in the samples so that your browser will load the HTTPS version if your page is HTTPS, and the HTTP version if your page is HTTP. This prevents security warnings in the browser.