Load KML file into google earth plug in api

3,155 views
Skip to first unread message

Shea

unread,
Oct 15, 2009, 6:10:22 PM10/15/09
to KML Developer Support - Google Earth Plug-in
I have some coding experience but am new to this google api (kml,
JavaScript, etc) I am a graduate student and recently starting
learning how to code, to i guess get myself in more trouble.. , I
think the what I am trying to do is simple but having some troublen. I
am havign trouble knowing when and were to input different langauges
in to html like javescript or KML .
basically I have just created an api on a web page and am trying to
get eventually a handful of kml files to load in the google earth api.
As of now I am 1 not sure if i have the write code and two not sure
how to impliment that into what I already have. please help
working code below

<html>
<head>

<script src="http://www.google.com/jsapi?key=ABQIAAAANz_ToLgaX5q-
fj0wGWD_gxTlQm7HVMDMLp9_LZD_0l5N6yxCKhT31Mz_wA-us6ZF3S06nCBS-xw92w"> </
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);
ge.getNavigationControl().setVisibility(ge.VISIBILITY_SHOW);
setStatusBarVisibility()
setScaleLegendVisibility()
}

function failureCB(errorCode) {
}


google.setOnLoadCallback(init);
</script>

</head>
<body>
<div id="map3d" style="height: 600px; width: 750px;"></div>
</body>
</html>

code I want to us or implement in... or open to scrap this code for
any suggested


// in this sample we will attempt
// to fetch a KML file and show it

function finished(object) {
if (!object) {
// wrap alerts in API callbacks and event handlers
// in a setTimeout to prevent deadlock in some browsers
setTimeout(function() {
alert('Bad or null KML.');
}, 0);
return;
}
ge.getFeatures().appendChild(object);
var la = ge.createLookAt('');
la.set(37.77976, -122.418307, 25, ge.ALTITUDE_RELATIVE_TO_GROUND,
180, 60, 500);
ge.getView().setAbstractView(la);
}

// fetch the KML
var url = 'http://sketchup.google.com/' +
'3dwarehouse/download?
mid=28b27372e2016cca82bddec656c63017&rtyp=k2';
google.earth.fetchKml(ge, url, finished);

thank you for taking the time to look this over

Shea
Message has been deleted

fraser (Earth API Guru)

unread,
Oct 17, 2009, 8:26:53 AM10/17/09
to KML Developer Support - Google Earth Plug-in
Hi Shea,

The best thing to do would be to take a look at the examples in the
code playground.

Fetch Kml
http://code.google.com/apis/ajax/playground/?exp=earth#fetch_good_kml

Multiple Kml with checkboxes
http://code.google.com/apis/ajax/playground/?exp=earth#fetch_kml_(interactive,_checkboxes)

They, along with the other examples, should help you a lot.

F.

Shea

unread,
Oct 29, 2009, 7:08:55 PM10/29/09
to KML Developer Support - Google Earth Plug-in
Hey Thanks so much for the reply, Yeah since the treed I drastically
modified the first example to basically give me multiple boxes to
click. but when I did that the problem is both boxes call the same
file. I am stuck on how to tell javascript to grab the second file
path.

The second example I thought for sure was going to help but basicly
what is happening is the same kml file keeps loads when I check each
of the different boxes.

Thanks again Fraser for the reply

With your help I am now closer then I was so Thanks Again Fraser for
the reply

I put the code that is on the playground with some minor alteration to
show you what I am having trouble with. I have written a couple of
solutions that I thought would work but in reality they either do
nothing or keep the code from running.

I think my main problem is the size of my kml and the way its
configured File not sure tho.

!--
Copyright (c) 2009 Google inc.

You are free to copy and use this sample.
License can be found here: http://code.google.com/apis/ajaxsearch/faq/#license
-->

<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/
>
<title>Google Earth API Sample</title>
<script src="http://www.google.com/jsapi?
key=ABQIAAAA1XbMiDxx_BTCY2_FkPh06RRaGTYH6UMl8mADNa0YKuWNNa8VNxQEerTAUcfkyrr6OwBovxn7TDAH5Q"></
script>
<script type="text/javascript">
function addSampleButton(caption, clickHandler) {
var btn = document.createElement('input');
btn.type = 'button';
btn.value = caption;

if (btn.attachEvent)
btn.attachEvent('onclick', clickHandler);
else
btn.addEventListener('click', clickHandler, false);

// add the button to the Sample UI
document.getElementById('sample-ui').appendChild(btn);
}

function addSampleUIHtml(html) {
document.getElementById('sample-ui').innerHTML += html;
}
</script>
<script type="text/javascript">
var ge;

// store the object loaded for the given file... initially none of
the objects
// are loaded, so initialize these to null
var currentKmlObjects = {
'red': null,
'yellow': null,
'green': null
};

google.load("earth", "1");

function init() {
google.earth.createInstance('map3d', initCallback,
failureCallback);

addSampleUIHtml(
'<h2>Toggle KML Files:</h2>' +
'<input type="checkbox" id="kml-red-check" onclick="toggleKml
(\'red\');"/><label for="kml-red-check">Fire History 1990 2003</
label><br/>' +
'<input type="checkbox" id="kml-yellow-check"
onclick="toggleKml(\'yellow\');"/><label for="kml-yellow-check">Fire
History 1980 1989</label><br/>' +
'<input type="checkbox" id="kml-green-check" onclick="toggleKml
(\'green\');"/><label for="kml-green-check">Green Placemarks</
label><br/>'
);
}

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

// add a navigation control
ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);

// add some layers
ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);

// fly to set location (smm)
var la = ge.createLookAt('');
la.set(34.1, -118.69,
0, // altitude
ge.ALTITUDE_RELATIVE_TO_GROUND,
0, // heading
30, // straight-down tilt at 30%
48000 // range (inverse of zoom)
);
ge.getView().setAbstractView(la);


// if the page loaded with checkboxes checked, load the
appropriate
// KML files
if (document.getElementById('kml-red-check').checked)
loadKml('red');

if (document.getElementById('kml-yellow-check').checked)
loadKml('yellow');

if (document.getElementById('kml-green-check').checked)
loadKml('green');

document.getElementById('installed-plugin-version').innerHTML =
ge.getPluginVersion().toString();
}

function failureCallback(errorCode) {
}

function toggleKml(file) {
// remove the old KML object if it exists
if (currentKmlObjects[file]) {
ge.getFeatures().removeChild(currentKmlObjects[file]);
currentKmlObject = null;
}

// if the checkbox is checked, fetch the KML and show it on
Earth
var kmlCheckbox = document.getElementById('kml-' + file + '-
check');
if (kmlCheckbox.checked)
loadKml(file);
}

function loadKml(file) {
var kmlUrl = 'http://sbroussard.yolasite.com/resources/
1990-2003FH.kml';

// fetch the KML
google.earth.fetchKml(ge, kmlUrl, function(kmlObject) {
// NOTE: we still have access to the 'file' variable (via JS
closures)

if (kmlObject) {
// show it on Earth
currentKmlObjects[file] = kmlObject;
ge.getFeatures().appendChild(kmlObject);
} else {
// bad KML
currentKmlObjects[file] = null;

// wrap alerts in API callbacks and event handlers
// in a setTimeout to prevent deadlock in some browsers
setTimeout(function() {
alert('Bad or null KML.');
}, 0);

// uncheck the box
document.getElementById('kml-' + file + '-check').checked =
'';
}
});
}

</script>
</head>
<body onload="init()" style="font-family: arial, sans-serif; font-
size: 13px; border: 0;">
<div id="sample-ui"></div>
<div id="map3d" style="width: 500px; height: 380px;"></div>
<br>
<div>Installed Plugin Version: <span id="installed-plugin-version"
style="font-weight: bold;">Loading...</span></div>
</body>
</html>




On Oct 17, 5:26 am, fraser (Earth API Guru) wrote:
> Hi Shea,
>
> The best thing to do would be to take a look at the examples in the
> code playground.
>
> Fetch Kmlhttp://code.google.com/apis/ajax/playground/?exp=earth#fetch_good_kml
>
> Multiple Kml with checkboxeshttp://code.google.com/apis/ajax/playground/?exp=earth#fetch_kml_(int...)
>
> They, along with the other examples, should help you a lot.
>
> F.
>
> On Oct 15, 11:10 pm, Shea wrote:
>
> > I have some coding experience but am new to thisgoogleapi(kml,
> >JavaScript, etc)  I am a graduate student and recently starting
> > learning how to code, to i guess get myself in more trouble.. , I
> > think the what I am trying to do is simple but having some troublen. I
> > am havign trouble knowing when and were to input different langauges
> > in to html like javescript or KML .
> > basically I have just created anapion a web page and am trying to
> >     // wrap alerts inAPIcallbacks and event handlers

jmatthews

unread,
Oct 29, 2009, 10:16:40 PM10/29/09
to KML Developer Support - Google Earth Plug-in
There is a lot there to look at and think about. I bet you've been
doing hours of that!

One thing I wonder is whether you have a missing "s", as follows:

currentKmlObject = null;

I searched your code, and every other instance uses currentKmlObjects
in the plural.

Try fixing that, if you agree it was an oversight, because it might
cause unrelated problems.

Now, here is your problem:

The code was written to assume your kml files are named, "red.kml",
"green.kml" and "yellow.kml". Are they? They are not.

I can tell this because in your loadkml() function, I see a different
name for the kmlUrl as follows: var kmlUrl = 'http://
sbroussard.yolasite.com/resources/
1990-2003FH.kml';

Before you put that in, I bet the original code had url defined by a
string that referenced the variable, "file".

You changed that, and defined the url to open as one thing, and one
thing only: 'http://sbroussard.yolasite.com/resources/
1990-2003FH.kml';

So, it will open that file every time. To work with multiple kml's,
that's why the google team writers originally used the variable,
"file." You hard-coded yours.

Additionally, I bet once your kml loads, it still does not compute the
bounds and set the view to go there (wherever it is). You'll want to
do that.

On a side note, I see the program actually closes and opens the kml
file as you check and un-check the box. You could use the toggle to
change from visible to invisible, which I would think would avoid
repetitively re-loading files you already loaded, which I assume would
be faster. Why close it, when you can make it invisible but leave it
in memory to make visible when you want?

I have been debugging my code, but you can go here and view the page
source in your browser. Note: I think I've found a bug where "fly-
to" does not work in Internet Explorer, so I recommend you look at it
through Firefox or Chrome.

http://sovereignstates.net/StateLegislators/VSLegislators.htm


jmatthews

unread,
Oct 29, 2009, 10:32:43 PM10/29/09
to KML Developer Support - Google Earth Plug-in


Oh, I forgot to tell you that when it was originally coded by the
google team, the variable "file" in loadkml() function was received
from the checkbox input at the beginning, where onclick is set to call
loadkml() and pass a parameter to it. IN this case, it is sending
"red", "yellow" or "blue" to loadkml(), depending on which button you
click.

In the original code, before you modified it, there was some coding
that set the url for the kml file as "somestring"+file
+"somestringending in .kml"

For example if it was "http://junk.net/"+cfile+".kml", it would open
the kml file called junk.net/red.kml if you clicked the red button.

Shea

unread,
Oct 30, 2009, 3:22:01 PM10/30/09
to KML Developer Support - Google Earth Plug-in
Jmatthews I love you man

I Got it to run! sweet. You nailed it right on the head with the
"http://junk.net/"+cfile+".kml" I did that originalay but when i
named my red yellow and blue files i capitalized one and not the
other....( which I vaguely remember doing to test to see if it was
case sensitive, but here is the thing I forgot about about doing
that. Ha and that one little mistake laid the first mistake to a list
of a 100 or so to follow. Ha I am so stoked, that one mistake killed 3
days. But I must say with your help I now have a better understanding
of the code.
Thank you Mattews
Buy the way love your website, it really looks great, I love your
table. Weird thing though Matthews the sight worked great, but when I
copied the source code into my free JavaScript editor to step through
it, for some reason the editor fails to run the code. not sure why
though. I am assuming b/c of the xml but not sure. And the code was
spaced out correctly. T
Anyways huge help MR. Jmatthews.
If you ever need any GIS advice or help feel free to hit me up.

Awesome!!!!!!

jmatthews

unread,
Nov 1, 2009, 3:52:16 PM11/1/09
to KML Developer Support - Google Earth Plug-in
Excellent, Shea! Glad I was able to help!

I've been making some progress on mine, too.

It's slow-going but steady, I guess.

I'd like to see what you have going on yours, because I will be
needing to add balloon features and other such things from a
navigation panel I am creating.

Who knows? I might just have to hit you up. This is pretty new to
me, still.

One thing I'd like to know is if I can speed up the initial load.
When the user goes to my site for the first time, it loads the US Map,
which is about a 3.5 meg kml. It must take a good 20-25 seconds to
load. I love what it does, but it's a bummer it loads slowly.

One thing I was wondering is whether you can set some sort of feature
to let the map go "active" before it reaches a certain resolution
level. I am starting out the view at high altitude, so if I am
waiting for street-level detail to be loaded and processed before the
map becomes interactive, maybe I could tell it to be interactive NOW,
and continue to load the detail. That would make the wait time seem
less.

Anyone have any ideas on this? I was thinking I saw something on this
in the reference.

jmatthews

unread,
Nov 1, 2009, 4:29:07 PM11/1/09
to KML Developer Support - Google Earth Plug-in
Here is what I was thinking in regards to speeding up the process of
making a map active before invisible detail is processed:

http://code.google.com/apis/earth/documentation/reference/interface_kml_lod.html

I don't know if that's what this function is designed to do as I am
not comfortable with all the jargon. If it allows me to say,
basically, "Since we start with an initial view at an altitude of
5,000 miles, there is no need to wait to make the map visible and
interactive until all the streets have been processed. Make it active
earlier, and continue to process the street-level data while the user
plays."

If that's what kmlLod is designed to do, please advise and let me know
how I'd use it.

I'd like to take a 25-second wait during loading a 3.5 meg kml, and
turn it into as little wait as possible.

Thanks.

Shea

unread,
Nov 4, 2009, 2:42:27 PM11/4/09
to KML Developer Support - Google Earth Plug-in
Hey man sorry it took me so long to get back to you, I want to assure
you that I have not forgot about you. I will look into this and let
you know soon. I have it scheduled to look at it tomorrow. I will
try to see if I can address that concept then. I do like your
thinking. I am hoping I can help. Good things take time, as you know,
so let me put the time in and I will get back to you.

Great.

Shea

Shea

unread,
Nov 5, 2009, 6:51:07 PM11/5/09
to KML Developer Support - Google Earth Plug-in
This concept seems to work fine for kml code but from what I hear
it is better for us to say in Javascript then trying to use kml.
To be honest at this point i am not sure how to implement
kml in to javascript or html properly without any glitches.
To be honest this is where I start to have a lot of question
we should be able to figure this out though.
I don't see why you cannot load kml file behind the window
and then bring it forward when you need it (i.e order bring
forward or sending backwards) I feel this would work fine.
Let me know what you think, and we can go from there.
I am trying to go camping this weekend so If I don't get
back to you today I will check the post on Monday.

Shea

Shea

unread,
Nov 5, 2009, 7:02:22 PM11/5/09
to KML Developer Support - Google Earth Plug-in
Hey watch the video on this page I am watching it now and it looks
like it is going to help a lot


http://code.google.com/apis/maps/

Aiman Shahpurwala

unread,
Feb 7, 2013, 12:11:08 PM2/7/13
to google-earth-...@googlegroups.com
Hi!

So this discussion on multiple KML files has really helped me out. I to am attempting to upload multiple KML files into google earth API. My KML files are not showing. I took example form your discussion to create the code I have, which I have copied onto this post. Please let me know if anyone has any suggestions. I have been working at this for a very long time, and cannot figure out what is wrong. Any help would be greatly appreciated! 

THANK YOU! 


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head> 
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/> 
    <title>Google Earth API Sample-Shea</title> 
    <script type="text/javascript"> 
      function addSampleButton(caption, clickHandler) { 
        var btn = document.createElement('input'); 
        btn.type = 'button'; 
        btn.value = caption; 

        if (btn.attachEvent) 
          btn.attachEvent('onclick', clickHandler); 
        else 
          btn.addEventListener('click', clickHandler, false); 

        // add the button to the Sample UI 
        document.getElementById('sample-ui').appendChild(btn); 
      } 

      function addSampleUIHtml(html) { 
        document.getElementById('sample-ui').innerHTML += html; 
      } 
    </script> 
    <script type="text/javascript"> 
    var ge; 

    // store the object loaded for the given file... initially none of the objects 
    // are loaded, so initialize these to null 
    var currentKmlObjects = { 
      '66760': null, 
      '68740': null, 
      '68760': null,
 '11070': null,
 '19370': null 
    }; 

    google.load("earth", "1"); 

    function init() { 
      google.earth.createInstance('map3d', initCallback, failureCallback); 

      addSampleUIHtml( 
        '<h2>Toggle KML Files:</h2>' + 
        '<input type="checkbox" id="kml-66760-check" onclick="toggleKml(\'66760\');"/><label for="kml-66760-check">Sneezy</label><br/>' + 
        '<input type="checkbox" id="kml-68740-check" onclick="toggleKml(\'68740\');"/><label for="kml-68740-check">Bashful</label><br/>' + 
        '<input type="checkbox" id="kml-68760-check" onclick="toggleKml(\'68760\');"/><label for="kml-68760-check">Dopey</label><br/>' +
'<input type="checkbox" id="kml-11070-check" onclick="toggleKml(\'11070\');"/><label for="kml-11070-check">Grumpy</label><br/>' +
'<input type="checkbox" id="kml-19370-check" onclick="toggleKml(\'19370\');"/><label for="kml-19370-check">Sleepy</label><br/>'
      ); 
    } 

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

      // add a navigation control 
      ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO); 

      // add some layers 
      ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true); 
      ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true); 

      // fly to set location (smm) 
var la = ge.createLookAt(''); 
la.set(35.5, -125.0, 
0, // altitude 
ge.ALTITUDE_RELATIVE_TO_GROUND, 
0, // heading 
20, // straight-down tilt at 30% 
1000000 // range (inverse of zoom) 
); 
ge.getView().setAbstractView(la); 


      // if the page loaded with checkboxes checked, load the appropriate 
      // KML files 
      if (document.getElementById('kml-66760-check').checked) 
        loadKml('66760'); 

      if (document.getElementById('kml-68740-check').checked) 
        loadKml('68740'); 

      if (document.getElementById('kml-68760-check').checked) 
        loadKml('68760'); 
 if (document.getElementById('kml-11070-check').checked) 
        loadKml('11070'); 
 if (document.getElementById('kml-19370-check').checked) 
        loadKml('19370'); 

      document.getElementById('installed-plugin-version').innerHTML = 
        ge.getPluginVersion().toString(); 
    } 

    function failureCallback(errorCode) { 
    } 

    function toggleKml(file) { 
      // remove the old KML object if it exists 
      if (currentKmlObjects[file]) { 
        ge.getFeatures().removeChild(currentKmlObjects[file]); 
        currentKmlObjects = null; 
      } 

      // if the checkbox is checked, fetch the KML and show it on Earth 
      var kmlCheckbox = document.getElementById('kml-' + file + '- check'); 
      if (kmlCheckbox.checked) 
        loadKml(file); 
    } 

    function loadKml(file) { 
      var kmlUrl = 'http://deeptow.whoi.edu/research/'+ file +'.kml'; 

      // fetch the KML 
      google.earth.fetchKml(ge, kmlUrl, function(kmlObject) { 
        // NOTE: we still have access to the 'file' variable (via JS closures) 

        if (kmlObject) { 
          // show it on Earth 
          currentKmlObjects[file] = kmlObject; 
          ge.getFeatures().appendChild(kmlObject); 
        } else { 
          // bad KML 
          currentKmlObjects[file] = null; 

          // wrap alerts in API callbacks and event handlers 
          // in a setTimeout to prevent deadlock in some browsers 
          setTimeout(function() { 
            alert('Bad or null KML.'); 
          }, 0); 

          // uncheck the box 
          document.getElementById('kml-' + file + '-check').checked = ''; 
        } 
      }); 
    } 

    </script> 
  </head> 
  <body onload="init()" style="font-family: arial, sans-serif; font- 
size: 13px; border: 0;"> 
    <div id="sample-ui"></div> 
    <div id="map3d" style="width: 500px; height: 380px;"></div> 
    <br> 
    <div>Installed Plugin Version: <span id="installed-plugin-version" 
style="font-weight: bold;">Loading...</span></div> 
  </body> 
</html> 

josh258

unread,
Feb 9, 2013, 9:56:29 PM2/9/13
to google-earth-...@googlegroups.com
Hello Aiman,
   There are a couple of minor mistakes with you page and then there is an issue of your kml url addresses. 

1. You beleive you have put an plural "s" onto object around line 105  under the function toggleKml(file).
Your code: currentKmlObjects = null; 
Change to: currentKmlObject = null; 

2. There is a space between the "-" and the "check" around line 110 a little further down under the toggleKml(file) function.
Your code: 
var kmlCheckbox = document.getElementById('kml-' + file + '- check'); 
Just take out the space between - and check.

3. Lastly, I could never get to your kml files even if I typed them into my address bar, so you might want to check the addresses of you kmls. I was able to fetch some of my kmls after I made the above changes. 

Hoped this helps,
Josh

Aiman Shahpurwala

unread,
Feb 14, 2013, 12:53:31 PM2/14/13
to google-earth-...@googlegroups.com
Hi Josh,

Thanks so much for the reply. We found those errors and fixed them but it still didn't work. The link for the kml file works fine on my computer, it just downloads the KML file. We are trying to generate a multiple linestrings on the google earth api. We realized this code works for other KML files but not for ours. Our KML file works fine in google earth so I am not sure why it won't work in the api. 

We are now trying to write code for loading the lat/long coordinates and compiling it into a linestring. 

Thanks for the help anyway, let us know if you have any other suggestions!

Aiman 

Josh L

unread,
Feb 14, 2013, 5:57:06 PM2/14/13
to google-earth-...@googlegroups.com
It may be useful if you paste the url of your site so we can debug there directly, rather than looking at the code in this thread.  Additionally, you may wish to paste it at somewhere like jsfiddle for easier debugging.

josh258

unread,
Feb 14, 2013, 7:23:32 PM2/14/13
to google-earth-...@googlegroups.com
Okay... I think I have it. I was able to download the kml files. You have your visibility in you kml set to "0". I took out <visibility>0</visibility> in each of you kmls. Here is a working page using the corrected kml along the html corrections in earlier post.


Source the page and you will be able to see and download the revised kmls.


Let me know if the links don't work,
Josh

Aiman Shahpurwala

unread,
Feb 18, 2013, 3:17:14 PM2/18/13
to google-earth-...@googlegroups.com
Wow thank you so much! We didn't realize that zero visibility was the problem! We had our KML to work for the google earth plugin and didn't realize that was the issue for the API!.

Thank you so much!!!!!!!!!!!!!!!!!!!!! :) 
Reply all
Reply to author
Forward
0 new messages