Search code examples
javascripthtmlevalgoogle-earth-plugin

Eval Google Earth code from textarea in script tag


I've got this code and i have to make it work without the text in the textarea. So the code which is written in the textarea should be in the script tag and it should work. Can anybody help me because i dont really know how the eval(document.getElementById('code').value works so i dont know how to integrate it. Here is the code i am talking from:

<html>
<head>
  <title>GEarthExtensions Samples - Drawing an extruded polygon</title>
  <script src="http://www.google.com/jsapi?key=ABQIAAAAsc0UQXoo2BnAJLhtpWCJFBTgHOxFyKCf35LCvsI_n4URElrkIhS9MkSlm_0NZWgrKFkOsnd5rEK0Lg" type="text/javascript"></script>
  <script src="extensions-0.2.1.pack.js" type="text/javascript"></script>
<script type="text/javascript">
/* <![CDATA[ */

var ge = null;
var gex = null;

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

google.setOnLoadCallback(function() {
  google.earth.createInstance('map3d', function(pluginInstance) {
    ge = pluginInstance;
    ge.getWindow().setVisibility(true);

    gex = new GEarthExtensions(pluginInstance);

    //gex.util.lookAt([0, 0], { range: 800000, tilt: 65 });

  }, function() {});
});


/* ]]> */
</script>
</head>
<body>
  <div id="map3d_container" style="width: 500px; height: 500px;">
    <div id="map3d" style="height: 100%"></div>
  </div>
<textarea id="code" style="font-family: monospace; width: 500px; height: 200px;">
gex.dom.clearFeatures();

var placemark = gex.dom.addPlacemark({
  polygon: {
    polygon: [],
    extrude: true,
    altitudeMode: geo.ALTITUDE_ABSOLUTE
  },
  style: {
    line: { width: 0 },
     poly: '#ff0'
  }
});

var coords = placemark.getGeometry().getOuterBoundary().getCoordinates();

gex.edit.drawLineString(placemark.getGeometry().getOuterBoundary(), {
  drawCallback: function(coordIndex) {
    var coord = coords.get(coordIndex);
    coords.setLatLngAlt(coordIndex,
         coord.getLatitude(), coord.getLongitude(), 100000);
 }
});
</textarea><br/>
<input type="button" onclick="eval(document.getElementById('code').value);" value="Run"/>
</body>
</html>

Solution

  • To run the code in script tag, you need to parse it first. DOMParser is a nice tool for that:

    function run(value) {
      var parser = new DOMParser();
      var doc = parser.parseFromString(value,"text/html"); // create DOM from value
      var code = doc.getElementsByTagName("script"); // get script tags from that DOM
      if(!code.length) eval(value); // no script tag, eval the value directly
      else eval(code[0].innerText); // eval the text from the first script tag
    }
    

    Test HTML code

    <textarea id="code">
    <script>
     alert("hello");
    </script>
    </textarea>
    <button onclick="run(document.getElementById('code').value)">Run</button>