0

I am studying because I want to publish my results through Google Earth Engine. Regarding the usage of if / else and ee.Algorithms.If(), I don't understand why both true case and false case work.

As per Code, I want to check if the value selected from ui.Select scorresponds to List v.

var s = ui.Select({
  
  items: [
    
      {label: 'A', value: 'A'},
      {label: 'B', value: 'B'},
    
    ]
  
});

var b = ui.Button('Go!');
b.onClick(b_function);

//var v = ee.List(['A', 'B', 'C']);
var v = ee.List(['C']);

function b_function(){
  
  ee.Algorithms.If(v.contains(s.getValue()), print('True!'), ui.root.add(ui.Label({value:'False!'})));

}

ui.root.add(s);
ui.root.add(b);

Is this possible even with a general if / else statement in google earth engine?

function b_function(){
  
  If(v.contains(s.getValue()){print('True!')}
  else(ui.root.add(ui.Label({'False!'});
  
}

1 Answer 1

1

The issue here is a mix up between client- and server-side. I would suggest that you read up on it here.

Your condition is server-side, so you cannot use a regular if statement. On the other hand, your actual actions are both client-side.

All arguments of ee.Algorithms.If() will be evaluated immediately, and both are performing client-side operations before the condition has even been evaluated. The common use of ee.Algorithms.If() is to use the return value, which will be different based on the condition. This server-side return value, ee.String in the example below, can then be turned into a client-side value using evaluate():

  ee.Algorithms.If(
    v.contains(s.getValue()), 
    'True!', 
    'False!'
  ).evaluate(function (value) {
    ui.root.add(ui.Label({value: value}))
  })

But you can just as well turn your condition into a client side object and use client-side conditional logic:

  v.contains(s.getValue()).evaluate(function (contains) {
    if (contains) {
      print('True!')
    } else {
      ui.root.add(ui.Label({value: 'False!'}))
    }
  })

https://code.earthengine.google.com/ff0b00c827899ebc44921cb7e2929c5a

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.