The easiest way to start learning about the Google Earth API is to see a simple example. The following JavaScript code creates a web page that embeds the Google Earth Plug-in:
<html>
<head>
<title>Hello, Google Earth</title>
<!-- *** Replace the key below below with your own API key, available at http://code.google.com/apis/maps/signup.html *** -->
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"> </script>
<script type="text/javascript">
google.load("earth", "1");
var ge = null;
function init() {
google.earth.createInstance("map3d", initCallback, failureCallback);
}
function initCallback(pluginInstance) {
ge = pluginInstance;
ge.getWindow().setVisibility(true); // required!
}
function failureCallback(errorCode) {
alert("Failure loading the Google Earth Plugin: " + errorCode);
}
</script>
</head>
<body onload="init()">
<div id="map3d_container" style="border: 1px solid silver; height: 500px;">
<div id="map3d" style="height: 100%;"></div>
</div>
</body>
</html>
You can download the example link above to edit and play around with the basic demo, but you'll have to replace the key in that file with your own Maps API key. (If you register a key for a particular directory, it works for all subdirectories as well.)
In this simple example, you need to do the following four things to get the Google Earth Plug-in to load on your web page:
script tag.div element to hold Google Earth.body tag's onLoad event.These steps are explained below.
<!-- *** Replace the key below below with your own API key, available at http://code.google.com/apis/maps/signup.html *** --> <script src="http://www.google.com/jsapi?key=ABCDEF"></script>
The http://www.google.com/jsapi?key=ABCDEF URL points to the location of the JavaScript file that includes all of the symbols and definitions you need for using the Google Earth API. Your page must contain a script tag pointing to this URL, using the key you received when you signed up for the API. In this example the key is shown as "ABCDEF."
For more information on this loading mechanism, visit the Google AJAX APIs documentation.
<div id="map3d_container" style="border: 1px solid silver; height: 600px; width: 800px;"> <div id="map3d" style="height: 100%;"></div> </div>
For Google Earth to display on a web page, you must reserve a spot for it. You
do this by creating a div element with a unique id. The
Earth API will insert an instance of the Google Earth Plug-in into this element.
In the example above, the div named "map3d" is the target element
for the plugin and its parent element, "map3d_container", is used for extra border
styling and sizing.
<body onload="init()">
While an HTML page renders, the document object model (DOM) is built out, and any external images and scripts are received
and incorporated into the document object. To ensure that our map is only placed on the page after the page has
fully loaded, we only execute the function which constructs the ge object once the <body> element
of the HTML page receives an onload event. Doing so avoids unpredictable behavior and gives us more
control on how and when the map draws.
The onload attribute is an example of an event handler. The Google Earth API also provides a number of
events that you can "listen" for to determine state changes. See Managing Events for more information.
A placemark is an easy-to-use feature that is used often in Google Earth. It marks a position on the Earth's surface, using a pushpin as the icon. In general, it marks the place the user is looking at or viewing. You can change the name and provide a custom icon for the placemark, and you can also add other geometry properties to it.
The following example creates a placemark marking the Google campus on the Earth's surface:
// Placemark
var placemark = ge.createPlacemark('');
placemark.setName('You are at Google');
// Placemark/Point
var point = ge.createPoint('');
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
point.setLatitude(lookAt.getLatitude());
point.setLongitude(lookAt.getLongitude());
placemark.setGeometry(point);
// Placemark/Style
var style = ge.createStyle('');
placemark.setStyleSelector(style);
// Placemark/Style/IconStyle
var icon = ge.createIcon('');
icon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png');
style.getIconStyle().setIcon(icon);
// add the placemark to Earth
ge.getFeatures().appendChild(placemark);
Here's what the placemark looks like in Google Earth:

You specify the following properties to create a placemark:
Once you have created a placemark, you can add balloon to describe it. The balloon fully supports the browser's HTML. You can create three types of balloons:
DIV balloonThe following example creates a Feature balloon:
var b = ge.createFeatureBalloon('');
b.setFeature(marker);
b.setMaxWidth(800);
ge.setBalloon(b);
The following example creates an informational window marking Mount Everest:
var b = ge.createHtmlStringBalloon('');
b.setMaxWidth(300);
b.setFeature(feature);
b.setContentString(
'<img src="http://www.google.com/intl/en_ALL/images/logo.gif">' +
'<font size=20>Mount Everest</font><br><font size=-2>on top of the world ' + 'window</font>');
ge.setBalloon(b);
View HTML String Balloon Example
View Custom Balloons Example
Here's what it looks like in Google Earth:
The following example creates a DIV balloon:
var b = ge.createHtmlDivBalloon('');
b.setMaxWidth(800);
b.setFeature(feature);
var div = document.createElement('DIV');
div.innerHTML =
'<img src="http://www.google.com/googlegulp/images/logo.gif"><br>'
+ '<a href="http://www.google.com/googlegulp/">Google Gulp</a>';
b.setContentDiv(div);
ge.setBalloon(b);
Notice that you can customize the look and feel of the informational window by including images, changing font size and so on.
To close the informational window, use the following JavaScript:
ge.setBalloon(null);
You can use the LookAt object to determine the point on the Earth that
is being viewed, the distance of the viewpoint from the point of interest, and
the angle of the view.
The following example moves the camera north by 7 degrees longitude and east by 7 degrees latitude:
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); lookAt.setLatitude(lookAt.getLatitude() + 7.0); lookAt.setLongitude(lookAt.getLongitude() + 7.0); ge.getView().setAbstractView(lookAt);
Many different types of paths can be created in Google Earth, and it is easy to be very creative with your data. A path is created by a lineString object and to define a connected set of line segments to create a path. When you use the LineString object, you need to specify whether or not to connect the LineString to the ground. The tessellate property breaks the line up into smaller sections.
In the following example, a white, jagged path is created:
// Placemark
var lineStringPlacemark = ge.createPlacemark('');
// Placemark/LineString (geometry)
var lineString = ge.createLineString('');
lineString.setTessellate(true);
lineString.getCoordinates().pushLatLngAlt( 0, 0, 0);
lineString.getCoordinates().pushLatLngAlt(.1, .05, 0);
lineString.getCoordinates().pushLatLngAlt( 0, .10, 0);
lineString.getCoordinates().pushLatLngAlt(.1, .15, 0);
lineString.getCoordinates().pushLatLngAlt( 0, .20, 0);
lineString.getCoordinates().pushLatLngAlt(.1, .25, 0);
lineStringPlacemark.setGeometry(lineString);
// append feature to Earth
ge.getFeatures().appendChild(lineStringPlacemark);
Here's the path in Google Earth:

You can change the appearance of your path by defining its color and width. The following JavaScript checks for a defined path, increases the width of the path in the previous example, and also changes its color to blue.
var lineStyle = lineStringPlacemark.getStyleSelector().getLineStyle();
lineStyle.setWidth(lineStyle.getWidth() + 2);
lineStyle.getColor().set('66ff0000');
View Line String Styling Example
Here's what the new path looks like in Google Earth:

You can use polygons to create simple buildings and other shapes.
In the following example, first, a white square is created by setting the outer boundary of the square and then the inner boundary:
// Placemark
var polygonPlacemark = ge.createPlacemark('');
// Placemark/Polygon (geometry)
var polygon = ge.createPolygon('');
polygonPlacemark.setGeometry(polygon);
// get center lookat
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
var lat = lookAt.getLatitude();
var lon = lookAt.getLongitude();
// Placemark/Polygon/outerBoundaryIs/LinearRing
var outer = ge.createLinearRing('');
outer.getCoordinates().pushLatLngAlt(lat - .05, lon - .05, 0);
outer.getCoordinates().pushLatLngAlt(lat - .05, lon + .05, 0);
outer.getCoordinates().pushLatLngAlt(lat + .05, lon + .05, 0);
outer.getCoordinates().pushLatLngAlt(lat + .05, lon - .05, 0);
polygon.setOuterBoundary(outer);
// Placemark/Polygon/innerBoundaryIs/LinearRing
var inner = ge.createLinearRing('');
inner.getCoordinates().pushLatLngAlt(lat - .02, lon - .02, 0);
inner.getCoordinates().pushLatLngAlt(lat - .02, lon + .02, 0);
inner.getCoordinates().pushLatLngAlt(lat + .02, lon + .02, 0);
inner.getCoordinates().pushLatLngAlt(lat + .02, lon - .02, 0);
polygon.getInnerBoundaries().appendChild(inner);
// add the placemark to Earth
ge.getFeatures().appendChild(polygonPlacemark);
Here is what the polygon looks like in Google Earth:

Like with a path, you can change the color and width of a polygon by specifying its color and width:
var lineStyle = polygonPlacemark.getStyleSelector().getLineStyle();
lineStyle.setWidth(lineStyle.getWidth() + 2);
lineStyle.getColor().set('66ff0000');
var polyStyle = polygonPlacemark.getStyleSelector().getPolyStyle();
polyStyle.getColor().set('660000ff');
The polygon is now red with a blue outline:

A network link contains a link property with an href (a hypertext reference) that loads a file.
The href in a link specifies the location of any of the following:
The specified file can be either a local file or a file on a remote server. In their simplest form, network links are a useful way to split one large KML file into smaller, more manageable files on the same computer.
The following example creates a network link:
// NetworkLink
var networkLink = ge.createNetworkLink('');
networkLink.setDescription('NetworkLink open to fetched content');
networkLink.setName('Open NetworkLink');
networkLink.setFlyToView(true);
// NetworkLink/Link
var link = ge.createLink('');
link.setHref('http://kml-samples.googlecode.com/svn/trunk/kml/NetworkLink/placemark.kml');
networkLink.setLink(link);
// add the network link to earth
ge.getFeatures().appendChild(networkLink);
Note: As with all other plugin functions, you can only use ge.createNetworkLink once your initCallback function has been called.
You can also use the above code inside of the initCallback function. See the above Hello, Earth section for details.
JavaScript within the browser is event driven, meaning that JavaScript responds to interactions by generating events, and expects a program to listen to interesting events. For example, within browsers, user mouse and keyboard interactions create events that propagate within the DOM. Programs interested in certain events will register JavaScript event listeners for those events and execute code when those events are received.
Events in the Google Earth API are handled by using utility functions within the GEvent namespace to register event listeners. Each Google Earth API object exports a number of named events. For example, the KmlPlacemark object exports click, dblclick, and move events, and a host of others as well. Each event happens within a given context, and can pass arguments that identify that context. For example, the mousemove event fires when the user moves the mouse within Google Earth.
In the following code example, you can see how events are managed:
function myEventListener(kmlEvent) {
var targetType = kmlEvent.getTarget().getType();
var currentTargetType = kmlEvent.getCurrentTarget().getType();
var button = kmlEvent.getButton());
var clientX = kmlEvent.getClientX();
var clientY = kmlEvent.getClientY();
var screenX = kmlEvent.getScreenX();
var screenY = kmlEvent.getScreenY();
var latitude = kmlEvent.getLatitude();
var longitude = kmlEvent.getLongitude();
var altitude = kmlEvent.getAltitude();
var didHitGlobe = kmlEvent.getDidHitGlobe();
var altKey = kmlEvent.getAltKey();
var ctrlKey = kmlEvent.getCtrlKey();
var shiftKey = kmlEvent.getShiftKey();
var timeStamp = kmlEvent.getTimeStamp();
}
// This will trigger myEventListener() when user clicks on 'placemark',
// and will pass in a KmlEvent object.
google.earth.addEventListener(placemark, "mousedown", myEventListener);
// This will trigger myEventListener() when user clicks on the globe,
// and will pass in a KmlEvent object.
google.earth.addEventListener(ge.getGlobe(), "mousedown", myEventListener);
// This will trigger myEventListener() when user clicks anywhere in the window,
// and will pass in a KmlEvent object.
google.earth.addEventListener(ge.getWindow(), "mousedown", myEventListener);