Bu kılavuzda, Earth Engine'de anında hesaplanan sonuçları içeren etkileşimli bir harita gösterimiyle web sayfası oluşturma adımları açıklanmaktadır. HTML, CSS ve JavaScript hakkında başlangıç veya orta düzeyde bilgi sahibi olan kullanıcılar için uygundur.
Aşağıda, bu kılavuzda oluşturacağınız etkileşimli haritanın demosunu bulabilirsiniz. Earth Engine'de hesaplanan ve farklı gri tonlarıyla gösterilen Büyük Kanyon'un arazi eğimini gösterir. Ek alanlarla ilgili sonuçları hesaplamak ve görüntülemek için haritayı kaydırıp yakınlaştırabilirsiniz. Demoya giriş yapmanız gerektiğini unutmayın.
Burada açıklanan yaklaşım genellikle tek sayfalık uygulamalar (SPA'lar) oluşturulurken kullanılır. SPA'da, sayfa sunucudan yeniden yüklenmeden uygulamanın tamamı web tarayıcısında kullanılabilir. Bu nedenle, bu uygulamalar için özel bir sunucu tarafı bileşeni geliştirilmesi ve barındırılması gerekmez.
Uygulamanın kodu kullanıcının web tarayıcısında (istemci tarafı yürütme olarak da bilinir) çalıştırılacağından geliştiriciler, hizmet hesabı özel anahtarları gibi hassas kimlik bilgilerini doğrudan uygulamaya yerleştirmemelidir. Bunun yerine, uygulamanın kullanıcıları, Earth Engine erişimi için kayıtlı kendi hesaplarını kullanarak kimlik doğrulaması yapmalıdır.
Bu kılavuzda şunları öğreneceksiniz:
- Kullanıcıların Earth Engine hesaplarını kullanarak oturum açmasına olanak tanıyan bir düğme gösterin.
- Earth Engine'de temel bir analiz tanımlayın.
- Maps JavaScript API'yi kullanarak sonuçları göstermek için etkileşimli bir harita yerleştirin.
Ön koşullar
Cloud projenizi ayarlama
- Başlamadan önce Set up your Earth Engine enabled Cloud Project (Earth Engine'in etkinleştirildiği Cloud projenizi oluşturma) başlıklı makaledeki talimatları uygulayın. "OAuth 2.0'ı ayarlama" bölümünde elde edilen istemci kimliğini not edin. Uygulamanız, kullanıcıların kendi Google Hesaplarıyla oturum açmasına izin vereceğinden "Hizmet hesabı oluşturma ve kaydetme" bölümünü atlayabilirsiniz.
- Projeniz için Maps JavaScript API'yi etkinleştirin.
Maps API anahtarı alma
Web uygulamanızda Maps JavaScript API'yi kullanmanıza olanak tanıyan bir API anahtarı edinmeyi öğrenmek için Maps JavaScript API belgelerindeki API anahtarını alma bölümüne bakın.
API anahtarınızla yalnızca yetkili isteklerin yapılmasını sağlamak için API anahtarını kısıtlama bölümündeki talimatları da uygulamanız önemle tavsiye edilir.
Uygulamanızı oluşturma
1. Adım: HTML sayfası oluşturma
Başlamak için temel bir HTML web sayfası tanımlayın:
<!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>Bu temel HTML'nin yaptığı birkaç şey vardır:
- Başlatma sırasında gösterilen haritanın boyutunu ve arka plan rengini tanımlamak için CSS stillerini kullanır.
- Tıklandığında
onSignInButtonClick()işlevini çağıran bir "Google ile oturum açın" düğmesi tanımlar. Bu işlev, sonraki bölümlerde JavaScript'te tanımlanacaktır. - Başlatıldıktan sonra haritayı içerecek boş bir öğe tanımlar.
- Aşağıda tanımlanan JavaScript kodunu tutmak için boş bir
<script>bloğu ekler.
2. adım: JavaScript'te davranışları tanımlama
Aşağıdaki adımlarda, JavaScript kodu doğrudan <script> etiketi içine yerleştirilebilir.
API'leri ayarlamak ve eşlemek için geri çağırmayı tanımlayın
Kullanıcı oturum açtıktan sonra çalışacak bir işlev tanımlayın. Earth Engine API yalnızca kullanıcının kimliği doğrulandıktan sonra başlatılabilir ve çağrılabilir. Bu konuyla ilgili daha fazla bilgiyi yakında paylaşacağız.
Bu örnekte Earth Engine ve Haritalar API'leri başlatılır, arazi eğimini isteğe bağlı olarak hesaplayan bir karo kaynağı oluşturulur ve karo kaynağı, Maps JavaScript API'si tarafından görüntülenen bir yer paylaşımı olarak haritaya eklenir:
// 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); }
Oturum açma düğmesi tıklamaları için işleyici tanımlama
Ardından, oturum açma düğmesi tıklandığında oturum açma pop-up'ını gösterecek bir işlev ekleyin. Başarılı olursa setUp() yöntemi çağrılır.
// 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); }
Bu geri çağırma, yukarıdaki HTML'deki düğmeyle onclick özelliği aracılığıyla ilişkilendirilir. Bu örnekte, sayfa yüklendiğinde oturum açma düğmesinin başlangıçta gizli olduğunu unutmayın. Sonraki bölümde, düğmeyi göstermeden önce kullanıcının oturum açıp açmadığını kontrol edeceğiz.
Ana giriş noktasını tanımlama
Şimdi sayfa yüklendiğinde ilk olarak yürütülecek üst düzey kodu tanımlayalım.
Kullanıcının oturum açıp açmadığını kontrol etmek için Earth Engine'in yerleşik kimlik doğrulama yardımcı işlevi ee.data.authenticateViaPopup() kullanılır. Kullanıcı oturum açmışsa işlev, uygun izinleri ister ve başarılı olursa Earth Engine ile Haritalar API'lerini başlatmak için setUp() işlevini çağırır.
Kullanıcı oturum açmamışsa bunun yerine oturum açma düğmesi gösterilir. Kullanıcı daha sonra düğmeyi tıklayarak onSignInButtonClick() işlevini tetikleyebilir. Bu işlev de pop-up'ı gösterir ve setUp() işlevini çağırarak süreci başlatır.
// 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 );
Kendiniz deneyin
Bu kılavuzda sunulan çözümün tamamı aşağıda verilmiştir. Örnek kodun sağ üst köşesinde üç düğme bulunur. Örneği JSFiddle'da açmak için en soldaki düğmeyi tıklayın.
YOUR_API_KEY ve YOUR_CLIENT_ID yerine Ön koşullar bölümünde edinilen Maps API anahtarını ve OAuth istemci kimliğini girin (Aşağıdaki kodda bu yer tutucuları tıklayarak otomatik olarak eklenmelerini sağlayabilirsiniz). Ayrıca 'my-project' kısmını Google Cloud proje kimliğinizle değiştirin.
<!-- 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>