API de Earth Engine en apps web del cliente

En esta guía, se muestra cómo compilar una página web con resultados de visualización de mapas interactivos que se calculan sobre la marcha en Earth Engine. Está destinada a personas con conocimientos básicos o intermedios de HTML, CSS y JavaScript.

A continuación, se muestra una demostración del mapa interactivo que crearás en esta guía. Muestra la pendiente del terreno del Gran Cañón calculada en Earth Engine, representada por diferentes tonos de gris. Puedes desplazar y acercar el mapa para calcular y mostrar resultados de áreas adicionales. Ten en cuenta que debes acceder a la demostración.

El enfoque que se describe aquí suele usarse cuando se crean aplicaciones de una sola página (SPA). En una SPA, se puede usar toda la app en un navegador web sin que se vuelva a cargar la página desde el servidor. Por lo tanto, estas apps no requieren el desarrollo ni el alojamiento de un componente personalizado del servidor.

Dado que el código de la app se ejecutará en el navegador web del usuario (también conocido como ejecución del cliente), los desarrolladores no deben incorporar credenciales sensibles, como las claves privadas de la cuenta de servicio, directamente en la aplicación. En su lugar, los usuarios de la aplicación deben autenticarse con sus propias cuentas que se registraron para el acceso a Earth Engine.

Con esta guía, aprenderás a hacer lo siguiente:

  1. Mostrar un botón que permita a los usuarios acceder con su cuenta de Earth Engine
  2. Definir un análisis básico en Earth Engine
  3. Incorporar un mapa interactivo para mostrar resultados con la API de Maps JavaScript

Requisitos previos

Configura tu proyecto de Cloud

  1. Antes de comenzar, sigue las instrucciones que se indican en Configura tu proyecto de Cloud habilitado para Earth Engine. Toma nota del ID de cliente que se obtuvo en la sección "Configura OAuth 2.0". Como tu aplicación permitirá que los usuarios accedan con su propia Cuenta de Google, puedes omitir la sección "Crea y registra una cuenta de servicio".
  2. Habilita la API de Maps JavaScript para tu proyecto.

Obtén una clave de API de Google Maps

Consulta Obtén la clave de API en la documentación de la API de Maps JavaScript para obtener información sobre cómo obtener una clave de API que te permita usar la API de Maps JavaScript en tu aplicación web.

Te recomendamos que también sigas las instrucciones de la sección Restringe la clave de API para asegurarte de que solo se realicen solicitudes autorizadas con tu clave de API.

Crea tu aplicación

Paso 1: Crea una página HTML

Para comenzar, define una página web HTML básica de la siguiente manera:

<!DOCTYPE html>
<html>
  <head>
    <style>
      /* Set the size of the div element that contains the map. */
      #map-container {
        height: 400px;
        width: 100%;
        background-color: #eee;
      }
    </style>
  </head>
  <body>
    <!-- The "Sign in with Google" button, initially hidden. -->
    <input
      id="g-sign-in"
      type="image"
      src="https://developers.google.com/identity/images/btn_google_signin_light_normal_web.png"
      onclick="onSignInButtonClick()"
      alt="Sign in with Google"
      hidden
    />

    <!-- Element where map will be added. -->
    <div id="map-container"></div>
    <script>
      // JavaScript code goes here.
    </script>
  </body>
</html>

Este HTML básico realiza varias acciones:

  • Usa estilos CSS para definir el tamaño y el color de fondo del mapa que se muestra durante la inicialización.
  • Define un botón "Acceder con Google" que llama a una función onSignInButtonClick() cuando se hace clic en él. Esta función se definirá en JavaScript en las siguientes secciones.
  • Define un elemento vacío que contendrá el mapa una vez que se inicialice.
  • Agrega un bloque <script> vacío para contener el código JavaScript definido a continuación.

Paso 2: Define comportamientos en JavaScript

En los siguientes pasos, el código JavaScript se puede colocar directamente dentro de la etiqueta <script>.

Define la devolución de llamada para configurar las APIs y el mapa

Define una función para realizar el trabajo una vez que el usuario haya accedido. La API de Earth Engine solo se puede inicializar e invocar una vez que se autenticó al usuario. Lo veremos en más detalle más adelante.

En este ejemplo, se inicializan las APIs de Earth Engine y Maps, se crea una fuente de mosaicos que calcula la pendiente del terreno a pedido y se agrega la fuente de mosaicos al mapa como una superposición que muestra la API de Maps JavaScript:

// Initializes Maps JavaScript API and Earth Engine API, instructing the map
// to pull tiles from Earth Engine and to overlay them on the map.
function setUpMap() {
  // Hide the sign-in button.
  document.getElementById("g-sign-in").setAttribute("hidden", "true");

  // Initialize the Earth Engine API. Must be called once before using the API.
  ee.initialize(null, null, null, null, null, 'my-project');

  // Get a reference to the placeholder DOM element to contain the map.
  const mapContainerEl = document.getElementById("map-container");

  // Create an interactive map inside the placeholder DOM element.
  const embeddedMap = new google.maps.Map(mapContainerEl, {
    // Pan and zoom initial map viewport to Grand Canyon.
    center: {lng: -112.8598, lat: 36.2841},
    zoom: 9,
  });

  // Obtain reference to digital elevation model and apply algorithm to
  // calculate slope.
  const srtm = ee.Image("CGIAR/SRTM90_V4");
  const slope = ee.Terrain.slope(srtm);

  // Create a new tile source to fetch visible tiles on demand and display them
  // on the map.
  const mapId = slope.getMap({min: 0, max: 60});
  const tileSource = new ee.layers.EarthEngineTileSource(mapId);
  const overlay = new ee.layers.ImageOverlay(tileSource);
  embeddedMap.overlayMapTypes.push(overlay);
}

Define el controlador para los clics en el botón de acceso

A continuación, agrega una función para mostrar la ventana emergente de acceso cuando se haga clic en el botón de acceso. Si tiene éxito, se llama al método setUp().

// Handles clicks on the sign-in button.
function onSignInButtonClick() {
  // Display popup allowing the user to sign in with their Google account and to
  // grant appropriate permissions to the app.
  ee.data.authenticateViaPopup(setUpMap);
}

Esta devolución de llamada se asocia con el botón en el HTML anterior a través de su atributo onclick. Ten en cuenta que, en este ejemplo, el botón de acceso se oculta inicialmente cuando se carga la página. En la siguiente sección, verificaremos si el usuario accedió antes de mostrar el botón.

Define el punto de entrada principal

Ahora definiremos el código de nivel superior que se ejecutará primero cuando se cargue la página. Usa la función auxiliar de autenticación integrada de Earth Engine ee.data.authenticateViaPopup() para verificar si el usuario ya accedió. Si el usuario accedió, la función solicita los permisos adecuados y llama a setUp() para inicializar las APIs de Earth Engine y Maps si tiene éxito.

De lo contrario, se muestra el botón de acceso. Luego, el usuario puede hacer clic en el botón para activar onSignInButtonClick(), que, a su vez, muestra la ventana emergente y llama a setUp() para iniciar el proceso.

// If the user is signed in, display a popup requesting permissions needed to
// run the app, otherwise show the sign-in button.
ee.data.authenticateViaOauth(
  // The OAuth Client ID defined above.
  CLIENT_ID,
  // Callback invoked immediately when user is already signed in.
  setUpMap,
  // Show authentication errors in a popup.
  alert,
  // Request permission to only read and compute Earth Engine data on behalf of
  // user.
  /* extraScopes = */ ['https://www.googleapis.com/auth/earthengine.readonly'],
  // Show sign-in button if reusing existing credentials fails.
  () => document.getElementById("g-sign-in").removeAttribute("hidden"),
  // Don't require ability to write and access Cloud Platform on behalf of the
  // user.
  /* opt_suppressDefaultScopes = */ true
);

Pruébalo

A continuación, se muestra la solución completa que se presenta en esta guía. En la esquina superior derecha del código de muestra, hay tres botones. Haz clic en el botón más a la izquierda para abrir la muestra en JSFiddle.

Reemplaza YOUR_API_KEY y YOUR_CLIENT_ID por la clave de API de Google Maps y el ID de cliente de OAuth que obtuviste en Requisitos previos (puedes hacer clic en estos marcadores de posición en el código que aparece a continuación para que se inserten automáticamente). También reemplaza 'my-project' por el ID de tu proyecto de Google Cloud.

<!-- Load Maps JavaScript API. For production apps, append you own ?key=YOUR_API_KEY. -->

<script src="https://maps.googleapis.com/maps/api/js?key="></script>
<script src="https://ajax.googleapis.com/ajax/libs/earthengine/0.1.365/earthengine-api.min.js"></script>
<!-- The "Sign in with Google" button, initially hidden. -->
<input
  id="g-sign-in"
  type="image"
  src="https://developers.google.com/identity/images/btn_google_signin_light_normal_web.png"
  onclick="onSignInButtonClick()"
  alt="Sign in with Google"
  hidden
/>

<!-- Element where map will be added. -->
<div id="map-container"></div>
/* Set the size of the div element that contains the map. */
  #map-container {
    height: 400px;
    width: 100%;
    background-color: #eee;
  }
// The OAuth Client ID from the Google Developers Console.
// REMINDER: Be sure to add a valid ID here!
const CLIENT_ID = "";

// Initializes Maps JavaScript API and Earth Engine API, instructing the map
// to pull tiles from Earth Engine and to overlay them on the map.
function setUpMap() {
  // Hide the sign-in button.
  document.getElementById("g-sign-in").setAttribute("hidden", "true");

  // Initialize the Earth Engine API. Must be called once before using the API.
  ee.initialize(null, null, null, null, null, 'my-project');

  // Get a reference to the placeholder DOM element to contain the map.
  const mapContainerEl = document.getElementById("map-container");

  // Create an interactive map inside the placeholder DOM element.
  const embeddedMap = new google.maps.Map(mapContainerEl, {
    // Pan and zoom initial map viewport to Grand Canyon.
    center: {lng: -112.8598, lat: 36.2841},
    zoom: 9,
  });

  // Obtain reference to digital elevation model and apply algorithm to
  // calculate slope.
  const srtm = ee.Image("CGIAR/SRTM90_V4");
  const slope = ee.Terrain.slope(srtm);

  // Create a new tile source to fetch visible tiles on demand and display them
  // on the map.
  const mapId = slope.getMap({min: 0, max: 60});
  const tileSource = new ee.layers.EarthEngineTileSource(mapId);
  const overlay = new ee.layers.ImageOverlay(tileSource);
  embeddedMap.overlayMapTypes.push(overlay);
}

// Handles clicks on the sign-in button.
function onSignInButtonClick() {
  // Display popup allowing the user to sign in with their Google account and to
  // grant appropriate permissions to the app.
  ee.data.authenticateViaPopup(setUpMap);
}

// If the user is signed in, display a popup requesting permissions needed to
// run the app, otherwise show the sign-in button.
ee.data.authenticateViaOauth(
  // The OAuth Client ID defined above.
  CLIENT_ID,
  // Callback invoked immediately when user is already signed in.
  setUpMap,
  // Show authentication errors in a popup.
  alert,
  // Request permission to only read and compute Earth Engine data on behalf of
  // user.
  /* extraScopes = */ ['https://www.googleapis.com/auth/earthengine.readonly'],
  // Show sign-in button if reusing existing credentials fails.
  () => document.getElementById("g-sign-in").removeAttribute("hidden"),
  // Don't require ability to write and access Cloud Platform on behalf of the
  // user.
  /* opt_suppressDefaultScopes = */ true
);
<!DOCTYPE html>
<html>
  <head>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/earthengine/0.1.365/earthengine-api.min.js"></script>
    <style>
      /* Set the size of the div element that contains the map. */
      #map-container {
        height: 400px;
        width: 100%;
        background-color: #eee;
      }
    </style>
  </head>
  <body>
    <!-- The "Sign in with Google" button, initially hidden. -->
    <input
      id="g-sign-in"
      type="image"
      src="https://developers.google.com/identity/images/btn_google_signin_light_normal_web.png"
      onclick="onSignInButtonClick()"
      alt="Sign in with Google"
      hidden
    />

    <!-- Element where map will be added. -->
    <div id="map-container"></div>
    <script>
      // The OAuth Client ID from the Google Developers Console.
      const CLIENT_ID = "YOUR_CLIENT_ID";
      
      // Initializes Maps JavaScript API and Earth Engine API, instructing the map
      // to pull tiles from Earth Engine and to overlay them on the map.
      function setUpMap() {
        // Hide the sign-in button.
        document.getElementById("g-sign-in").setAttribute("hidden", "true");
      
        // Initialize the Earth Engine API. Must be called once before using the API.
        ee.initialize(null, null, null, null, null, 'my-project');
      
        // Get a reference to the placeholder DOM element to contain the map.
        const mapContainerEl = document.getElementById("map-container");
      
        // Create an interactive map inside the placeholder DOM element.
        const embeddedMap = new google.maps.Map(mapContainerEl, {
          // Pan and zoom initial map viewport to Grand Canyon.
          center: {lng: -112.8598, lat: 36.2841},
          zoom: 9,
        });
      
        // Obtain reference to digital elevation model and apply algorithm to
        // calculate slope.
        const srtm = ee.Image("CGIAR/SRTM90_V4");
        const slope = ee.Terrain.slope(srtm);
      
        // Create a new tile source to fetch visible tiles on demand and display them
        // on the map.
        const mapId = slope.getMap({min: 0, max: 60});
        const tileSource = new ee.layers.EarthEngineTileSource(mapId);
        const overlay = new ee.layers.ImageOverlay(tileSource);
        embeddedMap.overlayMapTypes.push(overlay);
      }
      
      // Handles clicks on the sign-in button.
      function onSignInButtonClick() {
        // Display popup allowing the user to sign in with their Google account and to
        // grant appropriate permissions to the app.
        ee.data.authenticateViaPopup(setUpMap);
      }
      
      // If the user is signed in, display a popup requesting permissions needed to
      // run the app, otherwise show the sign-in button.
      ee.data.authenticateViaOauth(
        // The OAuth Client ID defined above.
        CLIENT_ID,
        // Callback invoked immediately when user is already signed in.
        setUpMap,
        // Show authentication errors in a popup.
        alert,
        // Request permission to only read and compute Earth Engine data on behalf of
        // user.
        /* extraScopes = */ ['https://www.googleapis.com/auth/earthengine.readonly'],
        // Show sign-in button if reusing existing credentials fails.
        () => document.getElementById("g-sign-in").removeAttribute("hidden"),
        // Don't require ability to write and access Cloud Platform on behalf of the
        // user.
        /* opt_suppressDefaultScopes = */ true
      );
    </script>
  </body>
</html>