Sự kiện
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Sự kiện được kích hoạt khi người dùng tương tác với một tiện ích hoặc thay đổi theo phương thức lập trình đối với một tiện ích. Để thực hiện một thao tác nào đó khi sự kiện xảy ra, hãy đăng ký một hàm gọi lại trên tiện ích bằng onClick()
(đối với ui.Map
hoặc ui.Button
) hoặc onChange()
(mọi thứ khác). Bạn cũng có thể chỉ định một lệnh gọi lại trong hàm khởi tạo. Các tham số cho lệnh gọi lại sự kiện thay đổi tuỳ thuộc vào loại tiện ích và sự kiện. Ví dụ: ui.Textbox
truyền giá trị chuỗi hiện đã nhập vào các hàm gọi lại sự kiện "nhấp". Hãy kiểm tra tài liệu tham khảo API trong thẻ Tài liệu để biết loại tham số được truyền đến các hàm gọi lại của từng tiện ích.
Ví dụ sau đây minh hoạ nhiều sự kiện bắt nguồn từ một hành động của người dùng là chỉ định một hình ảnh để hiển thị. Khi người dùng chọn một hình ảnh, một tiện ích chọn khác sẽ được cập nhật bằng các dải của hình ảnh và hiển thị dải đầu tiên trong bản đồ:
Trình soạn thảo mã (JavaScript)
// Load some images.
var dem = ee.Image('NASA/NASADEM_HGT/001');
var veg = ee.Image('NOAA/VIIRS/001/VNP13A1/2022_06_02')
.select(['EVI', 'EVI2', 'NDVI']);
// Make a drop-down menu of bands.
var bandSelect = ui.Select({
placeholder: 'Select a band...',
onChange: function(value) {
var layer = ui.Map.Layer(imageSelect.getValue().select(value));
// Use set() instead of add() so the previous layer (if any) is overwritten.
Map.layers().set(0, layer);
}
});
// Make a drop down menu of images.
var imageSelect = ui.Select({
items: [
{label: 'NASADEM', value: dem},
{label: 'VIIRS Veg', value: veg}
],
placeholder: 'Select an image...',
onChange: function(value) {
// Asynchronously get the list of band names.
value.bandNames().evaluate(function(bands) {
// Display the bands of the selected image.
bandSelect.items().reset(bands);
// Set the first band to the selected band.
bandSelect.setValue(bandSelect.items().get(0));
});
}
});
print(imageSelect);
print(bandSelect);
Xin lưu ý rằng khi người dùng chọn một hình ảnh, danh sách tên dải tần của hình ảnh sẽ được tải vào tiện ích bandSelect
, dải tần đầu tiên được đặt thành giá trị hiện tại và hàm onChange
của bandSelect
sẽ được kích hoạt tự động. Ngoài ra, hãy lưu ý việc sử dụng evaluate()
để không đồng bộ lấy giá trị của ComputedObject
do bandNames()
trả về. Tìm hiểu thêm trong phần Sự kiện không đồng bộ.
Ngừng nghe
Phương thức unlisten()
cung cấp khả năng xoá các hàm gọi lại đã đăng ký trên một tiện ích. Điều này rất hữu ích để ngăn các sự kiện kích hoạt chỉ xảy ra một lần hoặc trong một số trường hợp nhất định. Giá trị trả về của onClick()
hoặc onChange()
là một mã nhận dạng có thể được truyền đến unlisten()
để yêu cầu tiện ích ngừng gọi hàm. Để huỷ đăng ký tất cả sự kiện hoặc sự kiện thuộc một loại cụ thể, hãy gọi unlisten()
không có đối số hoặc đối số loại sự kiện (ví dụ: 'click'
hoặc 'change'
). Ví dụ sau đây minh hoạ unlisten()
để hỗ trợ việc mở và đóng bảng điều khiển:
Trình soạn thảo mã (JavaScript)
// Create a panel, initially hidden.
var panel = ui.Panel({
style: {
width: '400px',
shown: false
},
widgets: [
ui.Label('Click on the map to collapse the settings panel.')
]
});
// Create a button to unhide the panel.
var button = ui.Button({
label: 'Open settings',
onClick: function() {
// Hide the button.
button.style().set('shown', false);
// Display the panel.
panel.style().set('shown', true);
// Temporarily make a map click hide the panel
// and show the button.
var listenerId = Map.onClick(function() {
panel.style().set('shown', false);
button.style().set('shown', true);
// Once the panel is hidden, the map should not
// try to close it by listening for clicks.
Map.unlisten(listenerId);
});
}
});
// Add the button to the map and the panel to root.
Map.add(button);
ui.root.insert(0, panel);
Hãy quan sát rằng unlisten()
được dùng để ngăn Map
nghe các sự kiện nhấp để đóng bảng điều khiển khi bảng điều khiển đã đóng.
Sự kiện không đồng bộ
Nếu sử dụng kết quả của Earth Engine (chẳng hạn như kết quả số từ một lần giảm) trong một tiện ích, bạn sẽ cần lấy giá trị từ máy chủ. (Xem trang này để biết thông tin chi tiết về máy khách so với máy chủ trong Earth Engine). Để tránh treo toàn bộ giao diện người dùng trong khi giá trị đó được tính toán, bạn có thể sử dụng hàm evaluate()
để nhận giá trị một cách không đồng bộ. Hàm evaluate()
bắt đầu một yêu cầu cho một giá trị và khi giá trị đó đã sẵn sàng, hãy gọi một hàm gọi lại để thực hiện một thao tác nào đó với kết quả. Ví dụ: hãy xem xét một ứng dụng để lấy giá trị trung bình của một chuỗi thời gian NDVI tại một điểm:
Trình soạn thảo mã (JavaScript)
// Load and display an NDVI image.
var ndvi = ee.ImageCollection('LANDSAT/COMPOSITES/C02/T1_L2_8DAY_NDVI')
.filterDate('2014-01-01', '2015-01-01');
var vis = {min: 0, max: 1, palette: ['99c199', '006400']};
Map.addLayer(ndvi.median(), vis, 'NDVI');
// Configure the map.
Map.setCenter(-94.84497, 39.01918, 8);
Map.style().set('cursor', 'crosshair');
// Create a panel and add it to the map.
var inspector = ui.Panel([ui.Label('Click to get mean NDVI')]);
Map.add(inspector);
Map.onClick(function(coords) {
// Show the loading label.
inspector.widgets().set(0, ui.Label({
value: 'Loading...',
style: {color: 'gray'}
}));
// Determine the mean NDVI, a long-running server operation.
var point = ee.Geometry.Point(coords.lon, coords.lat);
var meanNdvi = ndvi.reduce('mean');
var sample = meanNdvi.sample(point, 30);
var computedValue = sample.first().get('NDVI_mean');
// Request the value from the server.
computedValue.evaluate(function(result) {
// When the server returns the value, show it.
inspector.widgets().set(0, ui.Label({
value: 'Mean NDVI: ' + result.toFixed(2),
}));
});
});
Khi người dùng nhấp vào một điểm trên bản đồ này, lệnh gọi reduceRegion()
sẽ được kích hoạt trên máy chủ. Thao tác này có thể mất chút thời gian. Để ngăn ứng dụng chặn trong khi Earth Engine đang tính toán, ví dụ này sẽ đăng ký một hàm gọi lại cho kết quả, cụ thể là computedValue.evaluate()
. Khi quá trình tính toán hoàn tất, kết quả sẽ hiển thị. Trong thời gian chờ đợi, một thông báo sẽ hiển thị để cho biết rằng quá trình tính toán đang diễn ra.
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-07-25 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-07-25 UTC."],[[["\u003cp\u003eEvents in the Earth Engine Code Editor are triggered by user interactions or programmatic changes to widgets, allowing you to execute specific actions in response.\u003c/p\u003e\n"],["\u003cp\u003eRegister callback functions to widgets using \u003ccode\u003eonClick()\u003c/code\u003e for ui.Map or ui.Button interactions and \u003ccode\u003eonChange()\u003c/code\u003e for other widgets to define actions upon event occurrence.\u003c/p\u003e\n"],["\u003cp\u003eUtilize \u003ccode\u003eunlisten()\u003c/code\u003e to remove registered callback functions, preventing events from triggering when no longer necessary, as demonstrated in the panel open/close example.\u003c/p\u003e\n"],["\u003cp\u003eFor operations involving Earth Engine results that require server-side computation, employ \u003ccode\u003eevaluate()\u003c/code\u003e to asynchronously retrieve values, ensuring a smooth user experience while preventing UI blocking.\u003c/p\u003e\n"]]],[],null,["# Events are fired by user interaction with a widget or a programmatic change to a\nwidget. To do something when the event occurs, register a callback function on the\nwidget with either `onClick()` (for `ui.Map` or\n`ui.Button`) or `onChange()` (everything else). You can also\nspecify a callback in the constructor. The parameters to event callbacks vary\ndepending on the widget and event type. For example, a `ui.Textbox` passes\nthe currently entered string value to its 'click' event callback functions. Check\nthe API reference in the **Docs** tab for the type of parameter passed to\nthe callback functions of each widget.\n\nThe following example demonstrates multiple events originating from a single user\naction of specifying an image to display. When the user selects an image, another\nselect widget is updated with the bands of the image and displays the first band\nin the map:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Load some images.\nvar dem = ee.Image('NASA/NASADEM_HGT/001');\nvar veg = ee.Image('NOAA/VIIRS/001/VNP13A1/2022_06_02')\n .select(['EVI', 'EVI2', 'NDVI']);\n\n// Make a drop-down menu of bands.\nvar bandSelect = ui.Select({\n placeholder: 'Select a band...',\n onChange: function(value) {\n var layer = ui.Map.Layer(imageSelect.getValue().select(value));\n // Use set() instead of add() so the previous layer (if any) is overwritten.\n Map.layers().set(0, layer);\n }\n});\n\n// Make a drop down menu of images.\nvar imageSelect = ui.Select({\n items: [\n {label: 'NASADEM', value: dem},\n {label: 'VIIRS Veg', value: veg}\n ],\n placeholder: 'Select an image...',\n onChange: function(value) {\n // Asynchronously get the list of band names.\n value.bandNames().evaluate(function(bands) {\n // Display the bands of the selected image.\n bandSelect.items().reset(bands);\n // Set the first band to the selected band.\n bandSelect.setValue(bandSelect.items().get(0));\n });\n }\n});\n\nprint(imageSelect);\nprint(bandSelect);\n```\n\nNote that when the user selects an image, the list of the image's band names is loaded\ninto the `bandSelect` widget, the first band is set to the current value,\nand the `onChange` function of `bandSelect` is fired\nautomatically. Also note the use of `evaluate()` to asynchronously get the\nvalue of the `ComputedObject` returned by `bandNames()`. Learn\nmore in the [Asynchronous Events section](/earth-engine/guides/ui_events#asynchronous-events).\n\nUnlistening\n-----------\n\nThe `unlisten()` method provides the ability to remove callback functions\nregistered on a widget. This is useful to prevent triggering events that should only\noccur once, or under certain circumstances. The return value of `onClick()`\nor `onChange()` is an ID that can be passed to `unlisten()` in\norder to make the widget stop calling the function. To unregister all events or events\nof a specific type, call `unlisten()` with no arguments or an event type (e.g.\n`'click'` or `'change'`) argument, respectively. The following\nexample demonstrates `unlisten()` to facilitate opening and closing of a panel:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Create a panel, initially hidden.\nvar panel = ui.Panel({\n style: {\n width: '400px',\n shown: false\n },\n widgets: [\n ui.Label('Click on the map to collapse the settings panel.')\n ]\n});\n\n// Create a button to unhide the panel.\nvar button = ui.Button({\n label: 'Open settings',\n onClick: function() {\n // Hide the button.\n button.style().set('shown', false);\n // Display the panel.\n panel.style().set('shown', true);\n\n // Temporarily make a map click hide the panel\n // and show the button.\n var listenerId = Map.onClick(function() {\n panel.style().set('shown', false);\n button.style().set('shown', true);\n // Once the panel is hidden, the map should not\n // try to close it by listening for clicks.\n Map.unlisten(listenerId);\n });\n }\n});\n\n// Add the button to the map and the panel to root.\nMap.add(button);\nui.root.insert(0, panel);\n```\n\nObserve that `unlisten()` is used to stop `Map` from listening\nfor click events to close the panel when the panel is already closed.\n\nAsynchronous Events\n-------------------\n\nIf you use an Earth Engine result (such the numerical output from a reduction) in a\nwidget, you will need to get the value from the server. (See the\n[this page](https://developers.google.com/earth-engine/client_server) for\ndetails about client vs. server in Earth Engine). To keep from hanging the entire UI\nwhile that value is computed, you can use the `evaluate()` function to\nget the value asynchronously. The `evaluate()` function begins a request\nfor a value, and when the value is ready calls a callback function to do something\nwith the result. For example, consider an application to get the mean value of an\nNDVI time series at a point:\n\n### Code Editor (JavaScript)\n\n```javascript\n// Load and display an NDVI image.\nvar ndvi = ee.ImageCollection('LANDSAT/COMPOSITES/C02/T1_L2_8DAY_NDVI')\n .filterDate('2014-01-01', '2015-01-01');\nvar vis = {min: 0, max: 1, palette: ['99c199', '006400']};\nMap.addLayer(ndvi.median(), vis, 'NDVI');\n\n// Configure the map.\nMap.setCenter(-94.84497, 39.01918, 8);\nMap.style().set('cursor', 'crosshair');\n\n// Create a panel and add it to the map.\nvar inspector = ui.Panel([ui.Label('Click to get mean NDVI')]);\nMap.add(inspector);\n\nMap.onClick(function(coords) {\n // Show the loading label.\n inspector.widgets().set(0, ui.Label({\n value: 'Loading...',\n style: {color: 'gray'}\n }));\n\n // Determine the mean NDVI, a long-running server operation.\n var point = ee.Geometry.Point(coords.lon, coords.lat);\n var meanNdvi = ndvi.reduce('mean');\n var sample = meanNdvi.sample(point, 30);\n var computedValue = sample.first().get('NDVI_mean');\n\n // Request the value from the server.\n computedValue.evaluate(function(result) {\n // When the server returns the value, show it.\n inspector.widgets().set(0, ui.Label({\n value: 'Mean NDVI: ' + result.toFixed(2),\n }));\n });\n});\n```\n\nWhen the user clicks a point on this map, a `reduceRegion()` call is triggered\non the server. This operation might take a while. To prevent the application from\nblocking while Earth Engine is computing, this example registers a callback function\nto the result, specifically `computedValue.evaluate()`. When the computation\nis finished, the result is displayed. In the meantime, a message is displayed to\nindicate that the computation is in progress."]]