Panduan ini menunjukkan cara membuat halaman web dengan tampilan peta interaktif yang menampilkan hasil yang dihitung secara langsung di Earth Engine. Tutorial ini cocok untuk orang yang memiliki pengetahuan tingkat pemula atau menengah dalam HTML, CSS, dan JavaScript.
Di bawah ini adalah demo peta interaktif yang akan Anda buat dalam panduan ini. Gambar ini menunjukkan kemiringan medan Grand Canyon yang dihitung di Earth Engine, yang direpresentasikan dengan berbagai nuansa abu-abu. Anda dapat menggeser dan memperbesar peta untuk menghitung dan menampilkan hasil untuk area tambahan. Perhatikan bahwa Anda harus login ke demo.
Pendekatan yang dijelaskan di sini biasanya digunakan saat membuat aplikasi web satu halaman (SPA). Di SPA, seluruh aplikasi dapat digunakan di browser web tanpa halaman dimuat ulang dari server. Oleh karena itu, aplikasi ini tidak memerlukan pengembangan dan hosting komponen sisi server kustom.
Karena kode aplikasi akan dijalankan di browser web pengguna (juga dikenal sebagai eksekusi sisi klien), developer tidak boleh menyematkan kredensial sensitif seperti kunci pribadi akun layanan langsung di aplikasi. Sebagai gantinya, pengguna aplikasi harus melakukan autentikasi menggunakan akun mereka sendiri yang telah terdaftar untuk akses Earth Engine.
Dalam panduan ini, Anda akan mempelajari cara:
- Menampilkan tombol yang memungkinkan pengguna login menggunakan akun Earth Engine mereka.
- Tentukan analisis dasar di Earth Engine.
- Sematkan peta interaktif untuk menampilkan hasil menggunakan Maps JavaScript API.
Prasyarat
Menyiapkan Project Cloud Anda
- Sebelum memulai, ikuti petunjuk di Menyiapkan Project Cloud yang mendukung Earth Engine. Catat Client ID yang diperoleh di bagian "Siapkan OAuth 2.0". Karena aplikasi Anda akan mengizinkan pengguna login dengan Akun Google mereka sendiri, Anda dapat melewati bagian "Buat dan daftarkan akun layanan".
- Aktifkan Maps JavaScript API untuk project Anda.
Mendapatkan kunci Maps API
Lihat Mendapatkan kunci API di dokumentasi Maps JavaScript API untuk mempelajari cara mendapatkan kunci API yang memungkinkan Anda menggunakan Maps JavaScript API di aplikasi web Anda.
Sebaiknya Anda juga mengikuti petunjuk di bagian Membatasi kunci API untuk memastikan hanya permintaan sah yang dibuat dengan kunci API Anda.
Buat aplikasi Anda
Langkah 1. Membuat halaman HTML
Untuk memulai, tentukan halaman web HTML dasar sebagai berikut:
<!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>HTML dasar ini melakukan beberapa hal:
- Menggunakan gaya CSS untuk menentukan ukuran dan warna latar belakang peta yang ditampilkan saat melakukan inisialisasi.
- Menentukan tombol "Login dengan Google" yang memanggil fungsi
onSignInButtonClick()saat diklik. Fungsi ini akan ditentukan di JavaScript di bagian berikutnya. - Menentukan elemen kosong yang akan berisi peta setelah diinisialisasi.
- Menambahkan blok
<script>kosong untuk menyimpan kode JavaScript yang ditentukan di bawah.
Langkah 2. Menentukan perilaku di JavaScript
Pada langkah-langkah berikutnya, kode JavaScript dapat ditempatkan langsung di dalam tag
<script>.
Tentukan callback untuk menyiapkan API dan peta
Tentukan fungsi untuk melakukan pekerjaan setelah pengguna login. Earth Engine API hanya dapat diinisialisasi dan dipanggil setelah pengguna diautentikasi. Informasi selengkapnya akan segera hadir.
Contoh ini menginisialisasi Earth Engine dan Maps API, membuat sumber ubin yang menghitung kemiringan medan sesuai permintaan, dan menambahkan sumber ubin ke peta sebagai overlay yang ditampilkan oleh Maps JavaScript API:
// 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); }
Menentukan pengendali untuk klik tombol login
Selanjutnya, tambahkan fungsi untuk menampilkan pop-up login saat tombol login diklik. Jika berhasil, metode setUp() akan dipanggil.
// 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); }
Callback ini dikaitkan dengan tombol di HTML di atas melalui atribut onclick-nya. Perhatikan bahwa dalam contoh ini, tombol login awalnya disembunyikan
saat halaman dimuat. Di bagian berikutnya, kita akan memeriksa apakah pengguna
login sebelum menampilkan tombol.
Menentukan titik entri utama
Sekarang, tentukan kode tingkat teratas yang akan dieksekusi terlebih dahulu saat halaman dimuat.
Fungsi ini menggunakan fungsi helper autentikasi bawaan Earth Engine
ee.data.authenticateViaPopup()
untuk memeriksa apakah pengguna sudah login. Jika pengguna login, fungsi akan meminta izin yang sesuai, dan memanggil setUp() untuk menginisialisasi Earth Engine dan Maps API jika berhasil.
Jika pengguna tidak login, tombol login akan ditampilkan. Pengguna
kemudian dapat mengklik tombol untuk memicu onSignInButtonClick(), yang pada gilirannya
menampilkan pop-up dan memanggil setUp() untuk memulai.
// 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 );
Cobalah sendiri
Solusi lengkap yang disajikan dalam panduan ini adalah sebagai berikut. Di sudut kanan atas kode contoh terdapat tiga tombol. Klik tombol paling kiri untuk membuka contoh di JSFiddle.
Ganti YOUR_API_KEY dan YOUR_CLIENT_ID dengan kunci Maps API dan ID klien OAuth yang diperoleh di Prasyarat (Anda dapat mengklik placeholder ini dalam kode di bawah untuk memasukkannya secara otomatis). Selain itu, ganti 'my-project' dengan project ID Google Cloud Anda.
<!-- 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>