이벤트

이벤트는 위젯과의 사용자 상호작용 또는 위젯의 프로그래매틱 변경에 의해 실행됩니다. 이벤트가 발생할 때 작업을 실행하려면 onClick()(ui.Map 또는 ui.Button의 경우) 또는 onChange()(그 외의 경우)를 사용하여 위젯에 콜백 함수를 등록합니다. 생성자에서 콜백을 지정할 수도 있습니다. 이벤트 콜백의 매개변수는 위젯 및 이벤트 유형에 따라 다릅니다. 예를 들어 ui.Textbox는 현재 입력된 문자열 값을 '클릭 이벤트' 콜백 함수에 전달합니다. 각 위젯의 콜백 함수에 전달되는 매개변수 유형은 문서 탭의 API 참조를 확인하세요.

다음 예는 표시할 이미지를 지정하는 단일 사용자 작업에서 발생하는 여러 이벤트를 보여줍니다. 사용자가 이미지를 선택하면 다른 선택 위젯이 이미지의 밴드로 업데이트되고 지도에 첫 번째 밴드가 표시됩니다.

코드 편집기(JavaScript)

// Load some images.
var dem = ee.Image('NASA/NASADEM_HGT/001');
var veg = ee.Image('NASA/VIIRS/002/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);

사용자가 이미지를 선택하면 이미지의 밴드 이름 목록이 bandSelect 위젯에 로드되고 첫 번째 밴드가 현재 값으로 설정되며 bandSelect의 onChange 함수가 자동으로 실행됩니다. 또한 evaluate()를 사용하여 bandNames()에서 반환된 ComputedObject 값을 비동기식으로 가져옵니다. 비동기 이벤트 섹션에서 자세히 알아보세요.

Unlisten

unlisten() 메서드는 위젯에 등록된 콜백 함수를 삭제하는 기능을 제공합니다. 이는 한 번만 발생하거나 특정 상황에서만 발생해야 하는 이벤트를 트리거하지 않도록 하는 데 유용합니다. onClick() 또는 onChange()의 반환 값은 위젯이 함수 호출을 중지하도록 unlisten()에 전달할 수 있는 ID입니다. 모든 이벤트 또는 특정 유형의 이벤트를 등록 취소하려면 인수 없이 또는 이벤트 유형(예: 'click' 또는 'change') 인수를 사용하여 unlisten()를 호출합니다. 다음 예는 패널을 쉽게 열고 닫을 수 있는 unlisten()를 보여줍니다.

코드 편집기(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);

unlisten()는 패널이 이미 닫혀 있을 때 패널을 닫기 위해 클릭 이벤트를 수신 대기하는 Map를 중지하는 데 사용됩니다.

비동기 이벤트

위젯에서 Earth Engine 결과(예: 축소의 수치 출력)를 사용하는 경우 서버에서 값을 가져와야 합니다. (Earth Engine의 클라이언트와 서버에 관한 자세한 내용은 이 페이지를 참고하세요.) 이 값을 계산하는 동안 전체 UI가 중단되지 않도록 하려면 evaluate() 함수를 사용하여 값을 비동기식으로 가져오면 됩니다. evaluate() 함수는 값 요청을 시작하고 값이 준비되면 콜백 함수를 호출하여 결과로 작업을 실행합니다. 예를 들어 한 지점에서 NDVI 시계열의 평균값을 가져오는 애플리케이션을 생각해 보세요.

코드 편집기(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),
    }));
  });
});

사용자가 이 지도의 한 지점을 클릭하면 서버에서 reduceRegion() 호출이 트리거됩니다. 이 작업은 시간이 걸릴 수 있습니다. Earth Engine이 계산하는 동안 애플리케이션이 차단되지 않도록 이 예시에서는 결과에 콜백 함수(구체적으로 computedValue.evaluate())를 등록합니다. 계산이 완료되면 결과가 표시됩니다. 그동안 계산이 진행 중임을 나타내는 메시지가 표시됩니다.