Announcement: All noncommercial projects registered to use Earth Engine before April 15, 2025 must verify noncommercial eligibility to maintain Earth Engine access.
Stay organized with collections
Save and categorize content based on your preferences.
Events are fired by user interaction with a widget or a programmatic change to a
widget. To do something when the event occurs, register a callback function on the
widget with either onClick() (for ui.Map or
ui.Button) or onChange() (everything else). You can also
specify a callback in the constructor. The parameters to event callbacks vary
depending on the widget and event type. For example, a ui.Textbox passes
the currently entered string value to its ‘click’ event callback functions. Check
the API reference in the Docs tab for the type of parameter passed to
the callback functions of each widget.
The following example demonstrates multiple events originating from a single user
action of specifying an image to display. When the user selects an image, another
select widget is updated with the bands of the image and displays the first band
in the map:
Note that when the user selects an image, the list of the image's band names is loaded
into the bandSelect widget, the first band is set to the current value,
and the onChange function of bandSelect is fired
automatically. Also note the use of evaluate() to asynchronously get the
value of the ComputedObject returned by bandNames(). Learn
more in the Asynchronous Events section.
Unlistening
The unlisten() method provides the ability to remove callback functions
registered on a widget. This is useful to prevent triggering events that should only
occur once, or under certain circumstances. The return value of onClick()
or onChange() is an ID that can be passed to unlisten() in
order to make the widget stop calling the function. To unregister all events or events
of a specific type, call unlisten() with no arguments or an event type (e.g.
'click' or 'change') argument, respectively. The following
example demonstrates unlisten() to facilitate opening and closing of a panel:
Observe that unlisten() is used to stop Map from listening
for click events to close the panel when the panel is already closed.
Asynchronous Events
If you use an Earth Engine result (such the numerical output from a reduction) in a
widget, you will need to get the value from the server. (See the
this page for
details about client vs. server in Earth Engine). To keep from hanging the entire UI
while that value is computed, you can use the evaluate() function to
get the value asynchronously. The evaluate() function begins a request
for a value, and when the value is ready calls a callback function to do something
with the result. For example, consider an application to get the mean value of an
NDVI time series at a point:
When the user clicks a point on this map, a reduceRegion() call is triggered
on the server. This operation might take a while. To prevent the application from
blocking while Earth Engine is computing, this example registers a callback function
to the result, specifically computedValue.evaluate(). When the computation
is finished, the result is displayed. In the meantime, a message is displayed to
indicate that the computation is in progress.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2023-10-06 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."]]