TransWikia.com

Google Earth Engine: Name parameters in custom function

Geographic Information Systems Asked on February 6, 2021

Situation

I’m working on a function with many parameters, and would like to be able to name them explicitly when calling the function.

I would usually call a function like this:

function get_sum(value_1, value2) {
var Sum = ee.Number(value_1).add(ee.Number(value2)); 
    print(Sum);
}
// Working
get_sum(75, 82);

Naming the parameters when calling the function leads to an error:

//Produces error
get_sum({value_1: 75, value2: 82});

enter image description here


Question

How do I do this? Is it something to do with served vs. client side?
Link to code

One Answer

This happens to be a matter of pure JavaScript; when you write a function and call it yourself, the Earth Engine API is not involved at all.

Here is how to write your function to accept {} named arguments:

function get_sum(args) {
    var value_1 = args.value_1;
    var value_2 = args.value_2;
    var Sum = ee.Number(value_1).add(ee.Number(value2)); 
    print(Sum);
}

(args is just a regular function parameter variable, not a special keyword, and you can call it whatever you like. args is a common name for this sort of thing.)

If you want to accept either named or un-named (positional) arguments, like the EE API functions do, it's significantly more messy and I'd recommend not bothering, but if you like, I can explain that too.

Note that if you misspell a name, the variables in the function will have the value undefined. If you want to help yourself out at the cost of writing more code, you can check for that:

function get_sum(named_args) {
    var value_1 = named_args.value_1;
    var value_2 = named_args.value_2;
    if (value_1 === undefined) throw new Error('get_sum: value_1 is missing');
    if (value_2 === undefined) throw new Error('get_sum: value_2 is missing');

    var Sum = ee.Number(value_1).add(ee.Number(value2)); 
    print(Sum);
}

Side note: Current JavaScript versions support a shortcut that makes this much more convenient:

function get_sum({value_1, value_2}) {
    var Sum = ee.Number(value_1).add(ee.Number(value2)); 
    print(Sum);
}

Unfortunately, the Earth Engine Code Editor does not currently permit running scripts that use newer JavaScript features. I mention this only because you may see references to this feature when reading about JavaScript.

Answered by Kevin Reid on February 6, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP