Earth Engine JavaScript API 會以 npm 套件的形式發布,並託管在 GitHub。以下操作說明將概略說明如何安裝 Google Earth Engine JavaScript API。如要使用 Earth Engine JavaScript API,您必須在電腦上安裝用戶端程式庫及其依附元件,然後設定驗證憑證。
JavaScript 用戶端程式庫不包含 Earth Engine 程式碼編輯器的所有功能。值得注意的是,按鈕、面板和圖表等使用者介面功能並未納入考量。
安裝用戶端程式庫
1. 設定 Node.js 和 npm
npm 是 JavaScript 和 Node.js 的套件管理工具。確認您已安裝 Node.js 6 以上版本和 npm 3 以上版本。
node --version npm --version
如有需要,請使用適用於您平台的官方安裝程式安裝這兩個版本。
2. 安裝 Earth Engine 用戶端程式庫
您可以使用下列指令,透過 npm 安裝用戶端程式庫:
npm install --save @google/earthengine
安裝完成後,用戶端程式庫會放在目前的專案目錄 node_modules/@google/earthengine/*
中。在日後的專案中,請以相同方式安裝用戶端。
3. 在應用程式中使用用戶端程式庫
在應用程式程式碼中要求 Earth Engine API:
var ee = require('@google/earthengine');
更新用戶端程式庫
使用 npm 將用戶端程式庫更新至最新版本。在目前專案目錄中:npm update @google/earthengine
進一步瞭解如何使用 npm 更新程式庫。
解除安裝用戶端程式庫
如要使用 npm 套件管理工具解除安裝,請執行下列指令:
npm uninstall --save @google/earthengine
這會從目前專案中移除 node_modules/@google/earthengine
,但不會影響同一部電腦上其他目錄中的任何專案。
建立 Cloud 專案並啟用 Earth Engine API
請按照這些操作說明建立 Cloud 專案,並啟用 Earth Engine API。
設定驗證憑證
Earth Engine API 會使用 OAuth 2.0 通訊協定驗證瀏覽器用戶端。針對 Node.js 中的伺服器端驗證,建議使用服務帳戶。網路應用程式可以使用這兩種方法,以下將說明各自的優缺點。
使用 OAuth 進行用戶端驗證
在網路瀏覽器中使用用戶端驗證功能後,應用程式的使用者就能使用自己的 Google 帳戶登入。這些使用者必須已獲授權存取 Earth Engine,且必須具備讀取應用程式所用資產的權限。
建立 OAuth 2.0 用戶端 ID 後,請按照下列步驟進行驗證:
// Load client library. var ee = require('@google/earthengine'); // Initialize client library and run analysis. var initialize = function() { ee.initialize(null, null, function() { // ... run analysis ... }, function(e) { console.error('Initialization error: ' + e); }); }; // Authenticate using an OAuth pop-up. ee.data.authenticateViaOauth(YOUR_CLIENT_ID, initialize, function(e) { console.error('Authentication error: ' + e); }, null, function() { ee.data.authenticateViaPopup(initialize); });
使用服務帳戶進行伺服器端驗證
使用伺服器端驗證時,私密金鑰會儲存在應用程式中,讓應用程式可透過服務帳戶存取 Earth Engine API。應用程式的使用者不需要擁有 Earth Engine 存取權,也不需要登入。
在 Node.js 中,用戶端程式庫只會提供伺服器端驗證。
建立新的服務帳戶後,請使用 JSON 私密金鑰進行驗證:
// Require client library and private key. var ee = require('@google/earthengine'); var privateKey = require('./.private-key.json'); // Initialize client library and run analysis. var runAnalysis = function() { ee.initialize(null, null, function() { // ... run analysis ... }, function(e) { console.error('Initialization error: ' + e); }); }; // Authenticate using a service account. ee.data.authenticateViaPrivateKey(privateKey, runAnalysis, function(e) { console.error('Authentication error: ' + e); });
測試安裝
如要測試驗證是否已正確設定,請執行下列指令碼:
var ee = require('@google/earthengine'); // Authenticate using one (but not both) of the methods below. ee.data.authenticateViaOauth(YOUR_CLIENT_ID); ee.data.authenticateViaPrivateKey(YOUR_PRIVATE_KEY); ee.initialize(); // Run an Earth Engine script. var image = new ee.Image('srtm90_v4'); image.getMap({min: 0, max: 1000}, function(map) { console.log(map); });
如果一切都已正確安裝,系統就會列印圖片的中繼資料。