API Earth Engine nelle app web lato client

Questa guida mostra come creare una pagina web con una visualizzazione interattiva della mappa risultati calcolati al volo in Earth Engine. È adatta a persone con conoscenze di base o intermedie di HTML, CSS e JavaScript.

Di seguito è riportata una demo della mappa interattiva che creerai in questa guida. Mostra la pendenza del terreno del Grand Canyon calcolata in Earth Engine, rappresentata da diverse tonalità di grigio. Puoi spostare e ingrandire la mappa per calcolare e visualizzare i risultati per aree aggiuntive. Tieni presente che devi accedere alla demo.

L'approccio descritto qui viene in genere utilizzato per creare applicazioni a una sola pagina (SPA). In una SPA, l'intera app è utilizzabile in un browser web senza che la pagina venga ricaricata dal server. Pertanto, queste app non richiedono lo sviluppo e l'hosting di un componente lato server personalizzato.

Poiché il codice dell'app verrà eseguito nel browser web dell'utente (noto anche come esecuzione lato client), gli sviluppatori non devono incorporare credenziali sensibili come le chiavi private del service account direttamente nell'applicazione. Gli utenti dell'applicazione devono invece autenticarsi utilizzando i propri account registrati per l'accesso a Earth Engine.

In questa guida, imparerai a:

  1. Mostra un pulsante che consente agli utenti di accedere utilizzando il proprio account Earth Engine.
  2. Definisci un'analisi di base in Earth Engine.
  3. Incorpora una mappa interattiva per visualizzare i risultati utilizzando l'API Maps JavaScript.

Prerequisiti

Configura il progetto cloud

  1. Prima di iniziare, segui le istruzioni riportate in Configura il progetto Cloud abilitato per Earth Engine. Prendi nota dell'ID client ottenuto nella sezione "Configurare OAuth 2.0". Poiché la tua applicazione consentirà agli utenti di accedere con il proprio Account Google, puoi saltare la sezione "Crea e registra un service account".
  2. Abilitare l'API Maps JavaScript per il tuo progetto.

Ottenere una chiave API di Google Maps

Consulta la sezione Ottieni la chiave API nella documentazione dell'API Maps JavaScript per scoprire come ottenere una chiave API che ti consenta di utilizzare l'API Maps JavaScript nella tua applicazione web.

Ti consigliamo vivamente di seguire anche le istruzioni riportate nella sezione Limitare la chiave API per assicurarti che con la tua chiave API vengano effettuate solo richieste autorizzate.

Crea la tua applicazione

Passaggio 1: Creare una pagina HTML

Per iniziare, definisci una pagina web HTML di base nel seguente modo:

<!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>

Questo codice HTML di base svolge diverse attività:

  • Utilizza gli stili CSS per definire le dimensioni e il colore di sfondo della mappa mostrata durante l'inizializzazione.
  • Definisce un pulsante "Accedi con Google" che chiama una funzione onSignInButtonClick() quando viene selezionato. Questa funzione verrà definita in JavaScript nelle sezioni successive.
  • Definisce un elemento vuoto che conterrà la mappa una volta inizializzata.
  • Aggiunge un blocco <script> vuoto per contenere il codice JavaScript definito di seguito.

Passaggio 2: Definisci i comportamenti in JavaScript

Nei passaggi successivi, il codice JavaScript può essere inserito direttamente all'interno del tag <script>.

Definisci il callback per configurare le API e la mappa

Definisci una funzione per eseguire un'operazione dopo che l'utente ha eseguito l'accesso. L'API Earth Engine può essere inizializzata e richiamata solo dopo l'autenticazione dell'utente. Maggiori dettagli a breve.

Questo esempio inizializza le API Earth Engine e Maps, crea un'origine delle tessere che calcola la pendenza del terreno su richiesta e aggiunge l'origine delle tessere alla mappa come overlay visualizzato dall'API 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);
}

Definisci il gestore per i clic sul pulsante di accesso

Successivamente, aggiungi una funzione per mostrare il popup di accesso quando viene fatto clic sul pulsante di accesso. In caso di esito positivo, viene chiamato il metodo 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);
}

Questo callback è associato al pulsante nel codice HTML riportato sopra tramite l'attributo onclick. Tieni presente che in questo esempio il pulsante di accesso è inizialmente nascosto quando la pagina viene caricata. Nella sezione successiva, verificheremo se l'utente ha eseguito l'accesso prima di visualizzare il pulsante.

Definisci l'entry point principale

Ora definiamo il codice di primo livello da eseguire per primo quando la pagina viene caricata. Utilizza la funzione helper di autenticazione integrata di Earth Engine ee.data.authenticateViaPopup() per verificare se l'utente ha già eseguito l'accesso. Se l'utente ha eseguito l'accesso, la funzione richiede le autorizzazioni appropriate e chiama setUp() per inizializzare le API Earth Engine e Maps in caso di esito positivo.

Se invece l'utente non ha eseguito l'accesso, viene visualizzato il pulsante di accesso. L'utente può quindi fare clic sul pulsante per attivare onSignInButtonClick(), che a sua volta mostra il popup e chiama setUp() per iniziare.

// 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
);

Fai una prova

Di seguito è riportata la soluzione completa presentata in questa guida. Nell'angolo in alto a destra del codice campione sono presenti tre pulsanti. Fai clic sul pulsante più a sinistra per aprire l'esempio in JSFiddle.

Sostituisci YOUR_API_KEY e YOUR_CLIENT_ID con la chiave API di Maps e l'ID client OAuth ottenuti in Prerequisiti (puoi fare clic su questi segnaposto nel codice riportato di seguito per inserirli automaticamente). Sostituisci anche 'my-project' con l'ID progetto 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>