Hướng dẫn này trình bày cách tạo một trang web có bản đồ tương tác hiển thị kết quả được tính toán ngay lập tức trong Earth Engine. Hướng dẫn này phù hợp với những người có kiến thức sơ cấp hoặc trung cấp về HTML, CSS và JavaScript.
Dưới đây là bản minh hoạ về bản đồ tương tác mà bạn sẽ tạo trong hướng dẫn này. Bản đồ này cho thấy độ dốc địa hình của Hẻm núi Grand Canyon được tính toán trong Earth Engine, được biểu thị bằng nhiều sắc thái xám. Bạn có thể di chuyển và phóng to bản đồ để tính toán và hiển thị kết quả cho các khu vực khác. Xin lưu ý rằng bạn phải đăng nhập vào bản minh hoạ.
Phương pháp được mô tả ở đây thường được dùng khi tạo ứng dụng một trang (SPA). Trong một SPA, toàn bộ ứng dụng đều có thể dùng được trong trình duyệt web mà không cần tải lại trang từ máy chủ. Do đó, các ứng dụng này không yêu cầu việc phát triển và lưu trữ một thành phần tuỳ chỉnh phía máy chủ.
Vì mã của ứng dụng sẽ chạy trong trình duyệt web của người dùng (còn gọi là quá trình thực thi phía máy khách), nên nhà phát triển không được nhúng trực tiếp các thông tin xác thực nhạy cảm như khoá riêng tư của tài khoản dịch vụ vào ứng dụng. Thay vào đó, người dùng ứng dụng phải xác thực bằng tài khoản của riêng họ đã đăng ký để truy cập vào Earth Engine.
Trong hướng dẫn này, bạn sẽ tìm hiểu cách:
- Hiển thị một nút cho phép người dùng đăng nhập bằng tài khoản Earth Engine của họ.
- Xác định một quy trình phân tích cơ bản trong Earth Engine.
- Nhúng một bản đồ tương tác để hiển thị kết quả bằng API JavaScript của Maps.
Điều kiện tiên quyết
Thiết lập Dự án trên đám mây
- Trước khi bắt đầu, hãy làm theo hướng dẫn trong Thiết lập Dự án trên đám mây đã bật Earth Engine. Ghi lại Mã ứng dụng khách nhận được trong phần "Thiết lập OAuth 2.0". Vì ứng dụng của bạn sẽ cho phép người dùng đăng nhập bằng Tài khoản Google của riêng họ, nên bạn có thể bỏ qua phần "Tạo và đăng ký tài khoản dịch vụ".
- Bật API JavaScript của Maps cho dự án của bạn.
Lấy khoá API Maps
Hãy xem bài viết Lấy khoá API trong tài liệu về API JavaScript của Maps để tìm hiểu cách lấy khoá API cho phép bạn sử dụng API JavaScript của Maps trong ứng dụng web.
Bạn nên làm theo hướng dẫn trong phần Hạn chế khoá API để đảm bảo chỉ các yêu cầu được uỷ quyền mới được thực hiện bằng khoá API của bạn.
Tạo ứng dụng
Bước 1. Tạo trang HTML
Để bắt đầu, hãy xác định một trang web HTML cơ bản như sau:
<!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>Chế độ HTML cơ bản này thực hiện một số việc:
- Sử dụng kiểu CSS để xác định kích thước và màu nền của bản đồ hiển thị trong khi khởi chạy.
- Xác định nút "Đăng nhập bằng Google" gọi hàm
onSignInButtonClick()khi được nhấp. Hàm này sẽ được xác định bằng JavaScript trong các phần tiếp theo. - Xác định một phần tử trống sẽ chứa bản đồ sau khi bản đồ được khởi chạy.
- Thêm một khối
<script>trống để chứa mã JavaScript được xác định bên dưới.
Bước 2. Xác định hành vi trong JavaScript
Trong các bước tiếp theo, bạn có thể đặt trực tiếp mã JavaScript bên trong thẻ
<script>.
Xác định lệnh gọi lại để thiết lập API và bản đồ
Xác định một hàm để thực hiện công việc sau khi người dùng đăng nhập. Bạn chỉ có thể khởi chạy và gọi API Earth Engine sau khi người dùng được xác thực. Chúng ta sẽ sớm nói thêm về vấn đề này.
Ví dụ này khởi chạy API Earth Engine và Maps, tạo một nguồn ô tính toán độ dốc địa hình theo yêu cầu và thêm nguồn ô vào bản đồ dưới dạng lớp phủ do API JavaScript của Maps hiển thị:
// 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); }
Xác định trình xử lý cho các lượt nhấp vào nút đăng nhập
Tiếp theo, hãy thêm một hàm để hiển thị cửa sổ bật lên đăng nhập khi nút đăng nhập được nhấp. Nếu thành công, phương thức setUp() sẽ được gọi.
// 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); }
Lệnh gọi lại này được liên kết với nút trong HTML ở trên thông qua thuộc tính onclick. Xin lưu ý rằng trong ví dụ này, nút đăng nhập ban đầu bị ẩn khi trang được tải. Trong phần tiếp theo, chúng ta sẽ kiểm tra xem người dùng đã đăng nhập hay chưa trước khi hiển thị nút.
Xác định điểm truy cập chính
Bây giờ, hãy xác định mã cấp cao nhất sẽ được thực thi trước tiên khi trang được tải.
Mã này sử dụng hàm trợ giúp xác thực tích hợp của Earth Engine là
ee.data.authenticateViaPopup()
để kiểm tra xem người dùng đã đăng nhập hay chưa. Nếu người dùng đã đăng nhập, hàm này sẽ yêu cầu các quyền thích hợp và gọi setUp() để khởi chạy API Earth Engine và Maps nếu thành công.
Nếu người dùng chưa đăng nhập, nút đăng nhập sẽ xuất hiện. Sau đó, người dùng có thể nhấp vào nút này để kích hoạt onSignInButtonClick(), từ đó hiển thị cửa sổ bật lên và gọi setUp() để bắt đầu.
// 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 );
Tự dùng thử
Sau đây là giải pháp hoàn chỉnh được trình bày trong hướng dẫn này. Ở góc trên cùng bên phải của mã mẫu có 3 nút. Hãy nhấp vào nút ở ngoài cùng bên trái để mở mẫu trong JSFiddle.
Thay thế YOUR_API_KEY và YOUR_CLIENT_ID bằng khoá API Maps và mã ứng dụng khách OAuth nhận được trong Điều kiện tiên quyết (bạn có thể nhấp vào các trình giữ chỗ này trong mã bên dưới để tự động chèn chúng). Ngoài ra, hãy
thay thế 'my-project' bằng mã dự án trên Google Cloud của bạn.
<!-- 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>