Google Earth API

Google Earth API Developer's Guide

  1. Introduction
  2. Audience
  3. Installing the Google Earth Plugin
  4. Using the Google Earth API
  5. Loading Additional Databases
  6. Troubleshooting
  7. Additional Resources

Introduction

Welcome to the developer documentation for the Google Earth API. The Google Earth Plugin and its JavaScript API let you embed the full power of Google Earth and its 3D rendering capabilities into your web pages. Just like in the Google Maps API, you can draw markers and lines—but in 3D!

See the Google Earth API developer forum if you have have questions about the API after reading this developer guide.

Audience

This documentation is designed for people familiar with JavaScript programming and object-oriented programming concepts. The Google Earth API is modeled after KML, so you should also consult Google's KML documentation.

The Google Earth Plugin

The Google Earth Plugin is currently supported on the following platforms:

  • Microsoft Windows (XP, and Vista)
    • Google Chrome 5.0+
    • Internet Explorer 7.0+
    • Firefox 3.0+
    • Flock 1.0+
  • Apple Mac OS X 10.5 and higher (Intel)
    • Google Chrome 5.0+
    • Safari 3.1+
    • Firefox 3.0+

Although the plugin and API may work correctly on other browsers that support NPAPI with npruntime extensions, these browsers are not officially supported.

Installation

To install the Google Earth Plugin, browse to any page in which the plugin is included (e.g. http://code.google.com/apis/ajax/playground/#hello,_earth).

Your browser will likely ask for permission before installing the plugin - click through to allow installation. Once the plugin is installed, you may need to refresh the page before the plugin displays correctly.

Uninstalling

  • Windows: Select Start > Programs (or All Programs) > Google Earth > Uninstall Google Earth Plug-in.
  • Mac: Delete /Library/Internet Plug-ins/Google Earth Web Plug-in.plugin before restarting your browser.

Using the Google Earth API

To load the Google Earth Plugin in your web page, you need to:

  1. Load the Google Earth API.
  2. Create a DIV element to hold the plugin.
  3. Create functions to initialize the plugin.
  4. Call the initialization functions once the page has loaded.

These steps are explained below.

Note: If you intend to use the Google Earth API under your Google Maps API for Business license, please refer to the Google Maps API for Business Developer's Guide for additional information.

Loading the Google Earth API

Place the following tag in the <head> of your HTML page:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>

The tag's src points to a JavaScript file with a single method, google.load, used to load individual Google APIs. Inside a new <script> tag, call:

google.load("earth", "1", {"other_params":"sensor=true_or_false"});

This tells Google to load the earth module into the google.earth namespace, and specifies version 1 (the last stable version of the API). To specify the latest test version of the API, specify "1.x".

The sensor parameter must be included, and indicates whether this application uses a sensor (such as a GPS locator) to determine the user's location. We've left this example as a variable true_or_false to emphasize that you must set this value to either true or false explicitly.

For more information on the loading mechanism, refer to the Google AJAX APIs documentation.

Creating a container for the plugin

The Google Earth Plugin is loaded into a DIV element with a unique id. Add the DIV to your page's <body> section:

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

In the example above, the DIV named map3d will become the target element for the plugin.

Creating initialization functions

You will create three functions as part of this step. In order, they will:

  • Attempt to create a new instance of the plugin.
  • Be called when the plugin instance is successfully created.
  • Be called if the instance cannot be created.

The first function looks like this:

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

google.earth.createInstance here shows three options: the DIV element into which the instance should be added, the function to call when success is returned, and the function to call if a failure is returned. In addition to these options, you can specify an alternative database to connect to, in order to display Mars imagery or to connect to an Earth Enterprise database.

The success callback function will contain all of the code required to set up your 'first run' experience - all of the objects and views that will first appear when your plugin instance is loaded in the browser. This function must contain the GEWindow.setVisibility method, setting the window visibility to true, so that the plugin is visible inside its DIV:

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

The failure callback can contain any code to deal with a failure to create the plugin instance. The error code is passed to the callback function, and can be repeated on the page or as an alert, if desired. Throughout this guide, the error callback function is left empty:

function failureCB(errorCode) {
}

Calling the initialization function when the page is loaded

The google namespace includes the setOnLoadCallback() function, which calls the specified function once the HTML page and requested APIs have been loaded. Using this function ensures that the plugin is not loaded until the page's DOM is completely built out.

google.setOnLoadCallback(init);

Complete example

<html>
<head>
  <title>Sample</title>
  <script type="text/javascript" src="https://www.google.com/jsapi"> </script>
  <script type="text/javascript">
    var ge;
    google.load("earth", "1", {"other_params":"sensor=true_or_false"});

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

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

    function failureCB(errorCode) {
    }

    google.setOnLoadCallback(init);
  </script>

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

Loading Additional Databases

You can load your own database to display on the Google Earth globe by specifying that database during initialization, or by calling addSideDatabase() on the Earth object. Loading a database at initialization will load only that database; the standard Google Earth imagery will not be loaded.

To load a database when initializing the plugin:

function init() {
  google.earth.createInstance('map3d', initCB, failureCB, {
    database: 'http://khmdb.google.com/?db=moon',
    username: '',
    password: '' // If your server requires these.
  });
}

Using addSideDatabase():

google.earth.addSideDatabase(
  ge, 'http://khmdb.google.com/?db=mars',
    sideDatabaseSuccess,
    sideDatabaseFail,
    {
      userName: '',
      password: ''
    }
);

For information about the Mars and Moon databases shown in the examples above, please read the Sky, Mars, and Moon chapter of this guide.

Disconnecting from a side database

To disconnect from a side database, call logout() on the side database object:

sideDB.logout()

Because a pointer to the database needs to exist, the side database must have been added using addSideDatabase():

var sideDB;

google.earth.addSideDatabase(
  ge, 'http://khmdb.google.com/?db=mars',
    sideDatabaseSuccess,
    sideDatabaseFail,
    {
      userName: '',
      password: ''
    }
);

function sideDatabaseSuccess(db) {
  sideDB = db;  
}

function sideDatabaseDisconnect() {
  sideDB.logout();
}

Google Maps Engine maps

Note: Google Maps Engine uses the term map to refer to a collection of imagery and vector layers; it is the equivalent of a database in Google Earth Enterprise Fusion Pro. For more information, please refer to the Terminology section of the Tips for users of Google Earth Enterprise support article.

Google Maps Engine maps can be loaded into the plugin using the methods above. The URL to a specific map is obtained by clicking the Google Earth option in the Published Links section of any published map's Details page.

google.earth.addSideDatabase(
  ge, 'https://earthbuilder.google.com/10446176163891957399-13516001307527776624-4/kh/',
    sideDatabaseSuccess,
    sideDatabaseFail,
    {
      userName: '',
      password: ''
    }
);

View sample: https://developers.google.com/earth/documentation/samples/addSideDatabase_noauth

If your map is public, no additional steps are required. If your map is private, you'll need to provide authentication credentials.

Authentication for Google Maps Engine maps

Users can authenticate to your map using their Google Account, if you've granted them access in Maps Engine. This is done using an OAuth 2.0 token; for information, please refer to the OAuth 2.0 documentation.

An example of loading the Earth API with an OAuth 2.0 token is below. You'll need:

  • An application ID, obtained from the API Access page of the API Console.
  • A valid redirect URI, also configured in the API Console. In the example below, it's assumed that the redirect URI is set to the same value as the application's URI (i.e. the authentication process will return the user to the originating page once authentication is complete).
var ge;

// Google Maps API for Business users must specify their client ID when loading
// the Google Earth API.
// var params = {"other_params":"client=YOUR_MAPSFORBUSINESS_CLIENTID&sensor=false"};
var params = {"other_params":"sensor=false"};
google.load("earth", "1", params);

function init() {
  var hash_value = window.location.hash;
  if (!hash_value) {
    var redirect_url = "https://accounts.google.com/o/oauth2/auth";
    // The client_id value below is obtained from the APIs Console.
    // It is not the same as a Google Maps API for Business client ID.
    redirect_url += "?client_id=370755043334.apps.googleusercontent.com";
    redirect_url += "&redirect_uri=" + window.location.href;
    redirect_url += "&scope=https://www.googleapis.com/auth/earthbuilder.readonly"
                  + "%20https://www.googleapis.com/auth/userinfo.email";
    redirect_url += "&response_type=token";
    window.location = redirect_url;
    return;
  }

  if (hash_value[0] == "#") {
    hash_value = hash_value.slice(1);
  }

  var hash_parts = hash_value.split("&");
  for (var i = 0; i < hash_parts.length; ++i) {
    var name_value = hash_parts[i].split("=");
    if (name_value.length == 2) {
      var name = name_value[0];
      var value = name_value[1];
      if (name == "access_token") {
        g_oauth_token_value = value;
      }
    }
  }

  if (!g_oauth_token_value) {
    return;
  }

  var optArgs = {
    oauth2Info : {
      oauthToken: g_oauth_token_value,
      signingUrl: 'https://earthbuilder.google.com/'
    }
  };
  google.earth.createInstance('map3d', initCB, failureCB, optArgs);
}

function initCB(instance) {
  ge = instance;
  ge.getWindow().setVisibility(true);
  ge.getOptions().setStatusBarVisibility(true);
  ge.getNavigationControl().setVisibility(ge.VISIBILITY_AUTO);
  ge.getLayerRoot().enableLayerById(ge.LAYER_BORDERS, true);
  ge.getLayerRoot().enableLayerById(ge.LAYER_ROADS, true);

  var lookAt = ge.createLookAt('');
  lookAt.setLatitude(41.26);
  lookAt.setLongitude(-100.00);
  lookAt.setRange(800000.0);
  ge.getView().setAbstractView(lookAt);

  // Substitute a valid Maps Engine URL below. The URL is obtained
  // by clicking the Google Earth option in the Published Links
  // section of any published map's Details page.
  var earthDb = 'https://earthbuilder.google.com/01234-5678-9/kh/';
  google.earth.addSideDatabase(
    ge, earthDb,
    sideDatabaseSuccess,
    sideDatabaseFail,
    {
      userName: '',
      password: ''
    }
  );
}

function failureCB(errorCode) {
  alert(errorCode);
}

function sideDatabaseSuccess(db) {
  db.setDrawOrder(2);
}

function sideDatabaseFail() {
  alert('Failed to add side database connection.');
}

google.setOnLoadCallback(init);

Google Maps API for Business Client IDs

If you're a Google Maps API for Business customer, you must pass your client ID when loading the API.

var params = {"other_params":"client=YOUR_MAPSFORBUSINESS_CLIENTID&sensor=false"};
google.load("earth", "1", params);

Troubleshooting

If your code doesn't seem to be working, here are some approaches that might help you solve your problems:

  • Use a JavaScript debugger. More information, including a list of common applications, is available in the Debugging section of this guide.
  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Search the developer forum. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.
  • See Additional Resources for more developer resources.

Additional Resources

This guide contains a number of working examples, linked from the Source line above the relevant code sample. In addition to the samples in this documentation, the following resources contain a number of examples:

  • AJAX APIs Playground - an interactive selection of examples that can be edited directly on the page. Your code can be exported and saved as JavaScript or HTML.
  • Earth API Demo Gallery - a collection of Earth API demos and samples, including community contributions.
  • Basic Samples - Investigate individual API features with these standalone samples containing full HTML.

If you need more information about Google Earth, KML, or Google Maps, refer to the following:

Developer channel

A developer channel plugin is available from http://earth.google.com/plugin/download-dev-plugin.html. This version of the plugin receives new features before they're released to the regular channel; it may however be less stable, and features launched only to the developer channel can be removed at any time.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.