Este guia mostra como criar uma página da Web com resultados de exibição de mapa interativo calculados em tempo real no Earth Engine. Ele é adequado para pessoas com conhecimento básico ou intermediário de HTML, CSS e JavaScript.
Confira abaixo uma demonstração do mapa interativo que você vai criar neste guia. Ele mostra a inclinação do terreno do Grand Canyon calculada no Earth Engine, representada por diferentes tons de cinza. É possível movimentar e dar zoom no mapa para calcular e mostrar resultados de outras áreas. Faça login na demonstração.
A abordagem descrita aqui é usada normalmente ao criar aplicativos de página única (SPAs). Em um SPA, todo o app pode ser usado em um navegador da Web sem que a página seja recarregada do servidor. Portanto, esses apps não exigem o desenvolvimento e a hospedagem de um componente personalizado do lado do servidor.
Como o código do app será executado no navegador da Web do usuário (também conhecido como execução do lado do cliente), os desenvolvedores não devem incorporar credenciais confidenciais, como chaves privadas de contas de serviço, diretamente no aplicativo. Em vez disso, os usuários do aplicativo precisam se autenticar usando as próprias contas registradas para acesso ao Earth Engine.
Neste guia, você vai aprender a:
- Mostrar um botão que permite que os usuários façam login usando a conta do Earth Engine.
- Definir uma análise básica no Earth Engine.
- Incorporar um mapa interativo para mostrar resultados usando a API Maps JavaScript.
Pré-requisitos
Configurar o projeto do Cloud
- Antes de começar, siga as instruções em Configurar o projeto do Cloud ativado para o Earth Engine. Anote o ID do cliente recebido na seção "Configurar o OAuth 2.0". Como o aplicativo vai permitir que os usuários façam login com a própria Conta do Google, pule a seção "Criar e registrar uma conta de serviço".
- Ative a API Maps JavaScript no seu projeto.
Gerar uma chave da API Maps
Consulte Gerar a chave de API na documentação da API Maps JavaScript para saber como receber uma chave de API que permite usar a API Maps JavaScript no seu aplicativo da Web.
Recomendamos que você também siga as instruções na seção Restringir a chave de API para garantir que apenas solicitações autorizadas sejam feitas com sua chave de API.
Criar o aplicativo
Etapa 1. Criar uma página HTML
Para começar, defina uma página HTML básica da Web da seguinte maneira:
<!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>Esse HTML básico faz várias coisas:
- Usa estilos CSS para definir o tamanho e a cor de plano de fundo do mapa mostrado durante a inicialização.
- Define um botão "Fazer login com o Google" que chama uma função
onSignInButtonClick()quando clicado. Essa função será definida em JavaScript nas próximas seções. - Define um elemento vazio que vai conter o mapa depois que ele for inicializado.
- Adiciona um bloco
<script>vazio para armazenar o código JavaScript definido abaixo.
Etapa 2. Definir comportamentos em JavaScript
Nas etapas a seguir, o código JavaScript pode ser colocado diretamente na
<script> tag.
Definir callback para configurar APIs e mapa
Defina uma função para trabalhar depois que o usuário fizer login. A API Earth Engine só pode ser inicializada e invocada depois que o usuário for autenticado. Falaremos mais sobre isso em breve.
Este exemplo inicializa as APIs Earth Engine e Maps, cria uma fonte de bloco que calcula a inclinação do terreno sob demanda e adiciona a fonte de bloco ao mapa como uma sobreposição mostrada pela 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); }
Definir o gerenciador para cliques no botão de login
Em seguida, adicione uma função para mostrar o pop-up de login quando o botão de login for clicado. Se for bem-sucedido, o método setUp() será chamado.
// 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); }
Esse callback está associado ao botão no HTML acima pelo atributo onclick. Neste exemplo, o botão de login fica inicialmente oculto quando a página é carregada. Na próxima seção, vamos verificar se o usuário fez login antes de mostrar o botão.
Definir o ponto de entrada principal
Agora, vamos definir o código de nível superior a ser executado primeiro quando a página for carregada.
Ele usa a função auxiliar de autenticação integrada do Earth Engine
ee.data.authenticateViaPopup()
para verificar se o usuário já fez login. Se o usuário tiver feito login, a função vai solicitar as permissões adequadas e chamar setUp() para inicializar as APIs Earth Engine e Maps se for bem-sucedida.
Se o usuário não tiver feito login, o botão de login será mostrado. Em seguida, o usuário pode clicar no botão para acionar onSignInButtonClick(), que, por sua vez, mostra o pop-up e chama setUp() para iniciar as coisas.
// 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 );
Sua vez de tentar
A solução completa apresentada neste guia é a seguinte. No canto superior direito do exemplo de código, há três botões. Clique no botão mais à esquerda para abrir a amostra no JSFiddle.
Substitua YOUR_API_KEY e YOUR_CLIENT_ID pela chave da API Maps e pelo ID do cliente OAuth recebidos nos pré-requisitos. Clique nesses marcadores de posição no código abaixo para que eles sejam inseridos automaticamente. Substitua também
replace 'my-project' pelo ID do projeto do 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>